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(); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答