【问题标题】:Search in Json column with Laravel使用 Laravel 在 Json 列中搜索
【发布时间】:2019-05-07 13:26:03
【问题描述】:

在我的电子邮件表中,我有一个名为To 的列,列类型为Json。这就是值的存储方式:

[
    {
        "emailAddress": {
            "name": "Test", 
            "address": "test@example.com"
        }
    }, 
    {
        "emailAddress": {
            "name": "Test 2", 
            "address": "test2@example.com"
        }
    }
]

现在我想要收集发送到“test@example.com”的所有电子邮件。我试过了:

DB::table('emails')->whereJsonContains('to->emailAddress->address', 'test@example.com')->get();

(见https://laravel.com/docs/5.7/queries#json-where-clauses) 但我没有得到匹配。有没有更好的使用 Laravel (Eloquent) 进行搜索的方法?

在调试栏中,我可以看到这个查询被“翻译”为:

select * from `emails` where json_contains(`to`->'$."emailAddress"."address"', '\"test@example.com\"'))

【问题讨论】:

  • 你用的是什么数据库?
  • 数据库 = MySQL 5.7.24
  • 只有1个邮箱时有效

标签: php mysql json laravel laravel-5


【解决方案1】:

箭头运算符在数组中不起作用。改用这个:

DB::table('emails')
   ->whereJsonContains('to', [['emailAddress' => ['address' => 'test@example.com']]])
   ->get()

【讨论】:

  • 有没有办法用通配符做到这一点?例如,Activity::whereJsonContains('properties', 'like', ['name' => "%$query%"])->get();
  • @EvanLalo 不,MySQL 不支持。
  • 你好,它工作正常,你能分享参考文件吗?
【解决方案2】:

我没有使用过 json 列,但正如文档所指,下面的代码应该可以正常工作。

DB::table('emails')
  ->where('to->emailAddresss->address','test@example.com')
  ->get();

【讨论】:

  • 我试过->where->whereJsonContains,但没有运气..
  • 您能否包含您的表架构,以便我们更好地了解该表。
  • 很确定是->where('to->"$.emailAddresss.address"','test@example.com')
  • @Tofandel 我在哪里找到了相关文档,我花了几个小时试图搜索 json 中的数组中的值。
【解决方案3】:

如果以 json 格式存储数组。只要有一个 ID 数组列表,我就这样做了。

items 是列名,$item_id 是我搜索的术语

// $item_id = 2
// items = '["2","7","14","1"]'
$menus = Menu::whereJsonContains('items', $item_id)->get();

【讨论】:

    【解决方案4】:

    你可以使用 where 子句和类似的条件

    DB::table('emails')->where('To','like','%test@example.com%')->get();
    

    或者,如果您使用 Eloquent 将模型映射到电子邮件表名称作为电子邮件

    Email::where('To','like','%test@example.com%')->get(); 
    

    【讨论】:

    • 他说的是json栏目。我觉得你错了
    • 如果有像 11test@example.com 这样的地址就会有问题,因为它也会被找到。所以它会起作用,但这不是最好的选择。
    猜你喜欢
    • 2017-11-23
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2021-10-15
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    相关资源
    最近更新 更多