【问题标题】:Laravel Query to select list entry in JSON fieldLaravel 查询以在 JSON 字段中选择列表条目
【发布时间】:2020-01-18 09:06:52
【问题描述】:

我使用 Laravel v6.11.0、nova v2.9.3 和 nova-flexible-content v0.1.13 将动态数据存储在 MySQL JSON 字段中。存储的数据如下所示:

[
  {
    "layout": "source",
    "key": "5ce8e0a877487fe5",
    "attributes": {
      "value": "342",
      "unit": "USD",
      "language": "en",
      "url": "http:\\/\\/google.com",
      "authority": "google.com",
      "entry_date": "2020-01-21",
      "date": "2019-12-21"
    }
  },
  {
    "layout": "source",
    "key": "a82393ce016e8c14",
    "attributes": {
      "value": "444",
      "unit": "USD",
      "language": "en",
      "entry_date": "2020-01-21",
      "url": "https:\\/\\/google.com",
      "authority": "TEST",
      "date": "2020-01-20"
    }
  }
]

我想知道是否可以构建一个 Laravel 查询来根据 authority 条目选择第二个条目?标准是:

  • url 应包含 google.com AND
  • authority 不应该是 google.com

我找到了https://laravel.com/docs/5.8/queries#json-where-clauses,但正在努力将正确的查询放在一起。也许有人可以给我一些关于如何做的指示?谢谢

【问题讨论】:

  • 您是每次存储整个数组还是 1 个对象?
  • 完整的 JSON 在一个 MySQL 列中 - 这就是组件自动存储它的方式。
  • 好的 db 列类型呢?是文本还是 json?
  • 这是一个 JSON 列

标签: php mysql laravel eloquent


【解决方案1】:

你可以在 Laracast 上参考这个discussion

$data = App\YourModel::whereRaw('JSON_CONTAINS(body->"$[*].attributes.url", "\"https://google.com\"")')
        ->orWhereRaw('JSON_CONTAINS(body->"$[*].id", "\"http://google.com\"")')
        ->whereRaw('not JSON_CONTAINS(body->"$[*].attributes.authority", "\"google.com\"")')
        ->get();

foreach ($data as $key => $row) {
    $bodyArr = json_decode($row->body);

    foreach ($bodyArr as $item) {

       if ((preg_match("/(http:\/\/www\.|https?:\/\/google.com)/i",$item->attributes->url)) && (strpos($item->attributes->authority, 'google.com') === false))  {
          dump($item);
          // YOUR CODE GOES HERE
       }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多