我在Laravel中的模型有一个linked_ids字符串字段,如下所示:echo $model->linked_ids
1,2,3,4,5
我想进行一个查询,获取linked_id中具有给定id的所有记录
目前我有:Model::where('linked_ids', 'LIKE', '%' . $model->id . '%');
,但这比我想要的选择更多(如果ex:$model->id为3=>选择:1,32,67(\
既然我不知道id将在什么位置,也不知道id会被订购,我该如何避免这种情况?我想雄辩地做到这一点,但也可以使用类似DB::raw((的东西来运行sql查询。
保留id的方法很糟糕,但如果你真的无法更改,你可以利用LazyCollections
并使用php进行过滤。
我确信有一种方法可以直接在MySQL(或者你使用的任何dbms(中实现,但这就是我所拥有的。
$id = 3;
Model::cursor()
->filter(function ($model) use ($id) {
return in_array($id, explode(',', $model->linked_ids));
})
// then chain one of these methods
->first(); // returns the first match or null
->collect(); // returns an IlluminateSupportCollection of the results after the filtering
->all(); // returns an array of Models after the filtering
->toArray(); // returns an array and transforms the models to arrays as well.
->toJson(); // returns a json string
请注意,这将仍然在不进行任何过滤的情况下执行SELECT * FROM table
(除非您在cursor()
之前链接一些where方法,但它不会将任何模型加载到内存中(这通常是Laravel中大型查询的瓶颈(