【问题标题】:laravel: JSON Field Comparison with Arraylaravel:JSON 字段与数组的比较
【发布时间】:2019-05-21 11:29:03
【问题描述】:
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 arrayfeatures 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();

【问题讨论】:

  • 我认为在您致电 get() 之前,您正在使用查询生成器,因此可能是与数据库列中的内容进行字符串比较。

标签: php mysql laravel laravel-query-builder


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    相关资源
    最近更新 更多