gpt4 book ai didi

php - Eloquent:复合 WhereIn 条件

转载 作者:行者123 更新时间:2023-11-29 05:01:41 25 4
gpt4 key购买 nike

是否有一种干净的方法来使用 Eloquent/laravel 来执行复合 WHERE ... IN () 条件。

查询结果为:

SELECT * FROM `table` WHERE (relation_type, relation_id) IN (('App\\Model', 1),('App\\Model', 3))

如您所见,这有助于对具有链接到其他 5 个模型的多态关系的实体进行单次查询提取。

我目前的解决方案是纯 MySQL:

//Example :array of array with Model name & id
$couples = [
['relation_type' => 'App\\Model', 'relation_id' => 1],
['relation_type' => 'App\\ModelTwo', 'relation_id' => 2],
['relation_type' => 'App\\ModelThree', 'relation_id' => 5],
['relation_type' => 'App\\ModelTwo', 'relation_id' => 20],
//...
['relation_type' => 'App\\Model', 'relation_id' => 999],
];
$query = "SELECT * FROM table WHERE ('relation_type', 'relation_id') IN (("
.implode('),(', array_map(function ($entry) {
return "'".$entry['relation_type']."',".$entry['relation_id']; //I know , in relation_type the '\' needs to be escaped.
}, $couples))
."))";
$results = \DB::select($query);
}

最佳答案

首先,您可以在列和值中都放入 DB::raw,这将解决使 SQL 查询正确的问题,我在 MySql 5.7< 上测试了以下内容 并且有效。 Db::raw 只是将原始字符串添加到查询中,注入(inject)可能很危险。

->whereIn(DB::raw('(relation_type, relation_id)'), [DB::raw("('App\\Model', '2')")])

现在我们只需要将您的数组转换为该结构,我的方法是 array_map foreach 也可以做到这一点。

$couples = array_map(function ($item) {
$type = $item['relation_type'];
$id = $item['relation_id'];

return DB::raw("('$type', '$id')");
}, $couples);

然后用一个简单的 Laravel 查询调用它,你应该可以开始了。

$models = Model::whereIn(DB::raw('(relation_type, relation_id)'), $couples)->get()

关于php - Eloquent:复合 WhereIn 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57789986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com