douluoqiu4538 2016-04-14 08:54 采纳率: 100%
浏览 38
已采纳

PostgreSQL表中的JSON数据的搜索列

I need to store some JSON data in PostgreSQL table to use it as dynamic route generator. The migration is simple:

Schema::create($this->tablename, function (Blueprint $table)
{
    $table->increments('id');
    $table->string("uri", 123);
    $table->json("middleware")->nullable();
    $table->string("as", 123)->nullable();
}

I store the data this way:

$a = new Route();
$a->uri = "/test1";
$a->middleware=json_encode(["auth","web"]);
$a->as = "TestController@test";
$a->save();

So let's say that I need to filter all the routes that have auth middleware. How can I do it?

When I try

Route::where('middleware', 'AS', 'auth')->get();

...I get an error. Is it possible to use it like that?

I use Laravel 5.2 and PostgreSQL 9.3.12.

Edit

If you are using PostgreSQL 9.4 or later and have Laravel framework with version bigger than 5.2.29 you can use this syntax:

Route::where('middleware','@>','"auth"')->get();
  • 写回答

1条回答 默认 最新

  • duanchen1937 2016-04-18 20:57
    关注

    Change where to whereRaw and query for json field

    Route::whereRaw("middleware->> 'auth'")->get(); 
    

    Or

    Route::whereRaw("middleware::json->> 'auth'")->get(); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#中的编译平台的区别影响
  • ¥15 软件供应链安全是跟可靠性有关还是跟安全性有关?
  • ¥15 电脑蓝屏logfilessrtsrttrail问题
  • ¥20 关于wordpress建站遇到的问题!(语言-php)(相关搜索:云服务器)
  • ¥15 【求职】怎么找到一个周围人素质都很高不会欺负他人,并且未来月薪能够达到一万以上(技术岗)的工作?希望可以收到写有具体,可靠,已经实践过了的路径的回答?
  • ¥15 Java+vue部署版本反编译
  • ¥100 对反编译和ai熟悉的开发者。
  • ¥15 带序列特征的多输出预测模型
  • ¥15 Python 如何安装 distutils模块
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行