希望有人能帮助我,我需要在数据库中搜索类别 id = x 的项目
Hope anybody can help me, I need to search for items that have category id = x in the database
示例表格项目id,猫,姓名等...猫 = '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
,你应该使用查找 ,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 雄辩的 whereIn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!