【问题标题】:Laravel Eloquent : Get object from database using JSON column keyLaravel Eloquent:使用 JSON 列键从数据库中获取对象
【发布时间】:2025-11-29 05:30:01
【问题描述】:

我尝试使用以下代码使用 testId 列从我的订阅表中检索整个订阅对象。 testId 列被声明为“json”类型,但实际上,该列的内容是一个包含单个字符串的数组,如下所示:

 ["51602a95-73d1-4c24-b3b3-eee288b427e4"]

我尝试使用此代码获取订阅对象,但不起作用。如何通过在数组中搜索 testId 的值来调整这段代码以获取订阅对象?

function getSubscriptionByTestId($testId) {
   $subscription = Subscription::where('testId', $testId)->first();
   return $subscription;
}

【问题讨论】:

  • 看起来 Laravel 5.3 尝试允许使用 ->where("{column}->{value_or_index}", "{operator}", "{comparison}); 查询 JSON 列,有关更多详细信息,请参阅 mattstauffer.co/blog/…。请注意,如果您不在 Laravel 5.3 上,DB::raw() 查询很可能是您的最佳选择。

标签: php laravel laravel-5 orm eloquent


【解决方案1】:

如果所有值都类似于["51602a95-73d1-4c24-b3b3-eee288b427e4"],具体取决于您可以使用的数据库引擎:

$subscription = Subscription::where('testId','like', "%$testId%")->first();

【讨论】:

    【解决方案2】:

    您可以使用原始查询尝试以下操作。我还不确定如何用 Eloquent 处理这个问题,但会进一步调查。

        return DB::select(
          "SELECT * FROM subscription
          WHERE testId->\"$[0]\" = \"{$testId}\""        
        );
    

    【讨论】: