有没有一种干净的方法可以WHERE ... IN ()
使用 Eloquent/laravel 进行复合条件。
查询结果将是:
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);
}