Laravel 5雄辩的地方 [英] Laravel 5 eloquent whereIn
问题描述
希望有人可以帮助我,我需要在数据库中搜索类别ID = x的项目
Hope anybody can help me, I need to search for items that have category id = x in the database
表项示例 id,cats,name等... cats ='1,19'或仅是'19'或'1,9'
Example table items id,cats,name etc... cats = '1,19' or maybe just '19' or maybe '1,9'
因此,在此示例中,我需要搜索具有9个猫的项目
So for this example I need a to search for items that have cats with 9
我尝试了这个,但是当我搜索9时,它也会显示19
I tried this but when I search for 9 it also shows 19
$items = Items::where(function($query)use($cat) {
$query->where('cats', 'like', '%,'.$cat->id.'%');
$query->orWhere('cats', 'like', '%'.$cat->id.',%');
$query->orWhere('cats', 'like', '%'.$cat->id.'%');
})->orderBy('updated_at', 'DSC')->get();
我也尝试过
$items = Items::whereIn(explode(',', 'cats'), $cat->id)->get();
但是它不起作用
感谢您的帮助,以找到最简单快捷的方式
Appreciate any help to find the easiest and shorts way of doing this, regards
推荐答案
很难理解您要实现的目标,但我会尽力的.首先,正如@particus所提到的,最好的方法是在不需要担心此类事情时创建数据透视表.
It's quite hard to understand what you want to achieve but I'll try. First of all as @particus mentioned the best way is to create pivot table when you don't need to worry about such things.
但是如果您在以逗号分隔的列中有ID列表,则解决方案不存储类似的值
But the solution if you have list of ids in a columns separated by coma is not storing values like
1,2,3
,但始终在开头和结尾处添加,
,因此在这种情况下应为:
but always adding ,
at the beginning and at the end, so it should be in this case:
,1,2,3,
这样,如果表中有,19,2,3,
,并且要搜索值9
,则应使用look ,9,
字符串,例如:
This way, if you have in your table ,19,2,3,
and you want to search for value 9
, you should use look for ,9,
string, for example:
$id = 9;
$items = Items::where('column', LIKE '%,'.$id.',%')->get();
现在对于上述字符串,将找不到任何记录,但是如果您具有,9,2,3,
或仅具有,9,
,则将找到所需的记录.
Now for above string no record will be found, but if you have ,9,2,3,
or just ,9,
the desired record will be found.
这篇关于Laravel 5雄辩的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!