【问题标题】:Laravel whereJsonContains query not workingLaravel whereJsonContains 查询不起作用
【发布时间】:2021-03-24 11:41:42
【问题描述】:

我正在尝试这个查询:

$order = Order::whereJsonContains('products->id',$serial_no)->first();

但它不起作用,请帮我解决这个问题。提前致谢。

[
  {
    "id": 24,
    "name": "test product",
    "qnt": 3,
    "sale_price": 18,
    "buy_price": 14,
    "stock": 3,
    "total": 54,
    "company": {
      "id": 1,
      "name": "test company",
      "contact": "01521482467,5555555",
      "address": "fdsa fdsa fdsa fdsa fdsa",
      "is_active": 1
    },
    "brand": {
      "id": 1,
      "name": "Test Brand",
      "is_active": 1
    },
    "category": {
      "id": 1,
      "name": "Test",
      "is_active": 1
    }
  },
  {
    "id": 28,
    "name": "test2",
    "qnt": 1,
    "sale_price": 18,
    "buy_price": 12,
    "stock": 1,
    "total": 18,
    "company": {
      "id": 1,
      "name": "test company",
      "contact": "01521482467,5555555",
      "address": "fdsa fdsa fdsa fdsa fdsa",
      "is_active": 1
    },
    "brand": {
      "id": 1,
      "name": "Test Brand",
      "is_active": 1
    },
    "category": {
      "id": 2,
      "name": "Test2",
      "is_active": 1
    }
  }
]

【问题讨论】:

    标签: laravel eloquent laravel-8


    【解决方案1】:

    试试这些

    $order = Order::whereJsonContains('products', ['id' => $serial_no])->first();
    

    当你的 json 看起来像这样时

    {
        "id": 24,
        "name": "test product",
        "qnt": 3,
        "sale_price": 18,
        "buy_price": 14,
        "stock": 3,
        "total": 54,
        "company": {
          "id": 1,
          "name": "test company",
          "contact": "01521482467,5555555",
          "address": "fdsa fdsa fdsa fdsa fdsa",
          "is_active": 1
     }
    

    然后您的代码将正常工作。 但是你的JSONArray 中点赞

    [
       {
            "id": 24,
            "name": "test product",
            "qnt": 3,
            "sale_price": 18,
            "buy_price": 14,
            "stock": 3,
            "total": 54,
            "company": {
              "id": 1,
              "name": "test company",
              "contact": "01521482467,5555555",
              "address": "fdsa fdsa fdsa fdsa fdsa",
              "is_active": 1
         }
    ]
    

    所以你可以使用这些语法来解决你的问题

    $order = Order::whereJsonContains('field_name', ['object_key' => 'object_value'])->first();
    

    【讨论】:

      【解决方案2】:

      使用 get() 代替 first() 并重试。

      【讨论】:

        【解决方案3】:

        @md abdul karim 请检查您的 mysql 版本,以及 mysql json_contains 与 mysql 5.7 或更高版本一起使用。

        【讨论】:

        • mysql Ver 15.1 Distrib 10.3.25-MariaDB,适用于 debian-linux-gnu (x86_64)
        • 我不知道怎么做,但我的系统显示这个:(
        猜你喜欢
        • 2019-08-02
        • 1970-01-01
        • 1970-01-01
        • 2019-01-03
        • 2015-01-13
        • 1970-01-01
        • 2022-08-19
        • 2018-11-10
        • 1970-01-01
        相关资源
        最近更新 更多