PostgreSQL表中的JSON数据的搜索列

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();

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

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

我以这种方式存储数据: p>

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

所以我要说我需要过滤所有的 具有 auth code>中间件的路由。我该怎么做? p>

当我尝试 p>

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

...我收到错误。是否可以 像这样使用它? p>

我使用 Laravel 5.2 em>和 PostgreSQL 9.3.12 em>。 p>

编辑 h2>

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

  Route :: where('middleware','@>','“auth”') - > get(  ); 
  code>  pre> 
  div>

Change where to whereRaw and query for json field

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

Or

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