首页 > 解决方案 > laravel:JSON 字段与数组的比较

问题描述

laravel-5.7/mysql

在我的数据库中,我有一个这样的 json 格式字段:

字段名称:特点

[
    {"id": 1, "url": null, "name": "A"}, 
    {"id": 2, "url": null, "name": "B"}
]

同样在它的模型中,我写了这个

  protected $casts = [
    'features' => 'array'
  ];

现在我创建一个数组:

$features = array();

temp = array();
temp['id'] = 1;
temp['url'] = null;
temp['name'] = A;
$features[] = temp;

temp = array();
temp['id'] = 2;
temp['url'] = null;
temp['name'] = B;
$features[] = temp;

我如何在数据库中进行$features array 比较features field

ّ我检查了这些:

$fff = \App\Cart::whereFeatures($features)->get()->first();

或者

$fff = \App\Cart::whereFeatures(json_encode($features))->get()->first();

或者

$fff = \App\Cart::whereFeatures(json_encode($features,JSON_UNESCAPED_UNICODE))->get()->first();

标签: phpmysqllaravellaravel-query-builder

解决方案


使用原始表达式转换比较值:

$fff = \App\Cart::whereRaw('features = cast(? as json)', json_encode($features))->get();

推荐阅读