Laravel Eloquent:使用JSON列键从数据库获取对象
问题描述:
我试图使用以下代码从我的订阅表中使用testId列检索整个订阅对象。 testId列delclared为“JSON”类型,但在现实中,这个专栏的内容是一个字符串如下数组:Laravel Eloquent:使用JSON列键从数据库获取对象
["51602a95-73d1-4c24-b3b3-eee288b427e4"]
我试图让这个代码,但加时赛没有按”认购对象工作。我怎么能通过搜索testId的值到数组中来获得订阅对象的这段代码?
function getSubscriptionByTestId($testId) {
$subscription = Subscription::where('testId', $testId)->first();
return $subscription;
}
答
如果所有的值都像["51602a95-73d1-4c24-b3b3-eee288b427e4"]
这取决于你的数据库引擎可以使用:
$subscription = Subscription::where('testId','like', "%$testId%")->first();
答
您可以使用原始查询尝试以下操作。我不确定如何用雄辩处理这个问题,但会进一步调查。
return DB::select(
"SELECT * FROM subscription
WHERE testId->\"$[0]\" = \"{$testId}\""
);
它看起来像Laravel 5.3做出尝试在允许JSON列使用'的查询 - >在哪里( “{column} - > {value_or_index}”,“{operator}”,“{comparison}};',见https://mattstauffer.co/blog/new-json-column-where-and-update-syntax- in-laravel-5-3以获得更多细节。注意,如果你不在Laravel 5.3中,'DB :: raw()'查询很可能是你最好的选择。 –