【问题标题】:Search column of JSON data in PostgreSQL tablePostgreSQL 表中 JSON 数据的搜索列
【发布时间】:2016-08-05 17:09:33
【问题描述】:

我需要在 PostgreSQL 表中存储一些 JSON 数据以将其用作动态路由生成器。迁移很简单:

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

我是这样存储数据的:

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

假设我需要过滤所有具有auth 中间件的路由。我该怎么做?

当我尝试时

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

...我收到一个错误。可以这样用吗?

我使用 Laravel 5.2PostgreSQL 9.3.12

编辑

如果您使用的是 PostgreSQL 9.4 或更高版本,并且 Laravel 框架的版本大于 5.2.29,则可以使用以下语法:

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

【问题讨论】:

    标签: php json postgresql laravel laravel-5.2


    【解决方案1】:

    更改 whereRaw 的位置并查询 json 字段

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

    或者

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

    【讨论】:

    • 好的,我收到错误Datatype mismatch: 7 ERROR: argument of WHERE must be type boolean, not type text,如果我将输出转换为布尔值,它就可以正常工作Route::whereRaw("(middleware->>'auth')::boolean")->get();
    • 其实我可以使用这个语法:Route::where('middleware','@>','"auth"')->get(); since laravel this commit
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2021-06-15
    • 2017-12-02
    相关资源
    最近更新 更多