简体   繁体   English

Laravel 5 雄辩的 whereIn

[英]Laravel 5 eloquent whereIn

Hope anybody can help me, I need to search for items that have category id = x in the database希望任何人都可以帮助我,我需要在数据库中搜索类别 id = x 的项目

Example table items id,cats,name etc... cats = '1,19' or maybe just '19' or maybe '1,9'示例表项 id、cats、name 等...cats = '1,19' 或者可能只是 '19' 或者可能是 '1,9'

So for this example I need a to search for items that have cats with 9所以对于这个例子,我需要一个来搜索有 9 的猫的项目

I tried this but when I search for 9 it also shows 19我试过了,但是当我搜索 9 时,它也显示了 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();

I also tried something我也尝试了一些东西

$items = Items::whereIn(explode(',', 'cats'), $cat->id)->get(); 

but it doesn't work但它不起作用

Appreciate any help to find the easiest and shorts way of doing this, regards感谢任何帮助找到最简单和简短的方法,问候

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.首先,正如@particus 提到的,最好的方法是在您不需要担心这些事情时创建数据透视表。

But the solution if you have list of ids in a columns separated by coma is not storing values like但是,如果您在以昏迷分隔的列中有 id 列表的解决方案不是存储值,例如

1,2,3

but always adding , at the beginning and at the end, so it should be in this case:但总是增加,在开始和结尾,所以它应该是在这种情况下:

,1,2,3,

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:这样,如果您的表中有,19,2,3,并且您想搜索值9 ,则应使用查找,9,字符串,例如:

$id = 9; 
$items = Items::where('column', LIKE '%,'.$id.',%')->get();

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.现在对于上面的字符串,将找不到任何记录,但是如果您有,9,2,3,或只有,9,则会找到所需的记录。

Assuming you're using MySQL, you can use the FIND_IN_SET function.假设您使用的是 MySQL,您可以使用 FIND_IN_SET 函数。

$items = Items::whereRaw("FIND_IN_SET(".$cat->id.", cats)")->orderBy('updated_at', 'DESC')->get();

Please note, this will not use any indexes defined on the cats column.请注意,这不会使用在cats 列上定义的任何索引。 Storing array like data in a field is usually a big red flag.在字段中存储类似数据的数组通常是一个很大的危险信号。 You would benefit by normalizing this out now, rather than trying to work around the current design.现在将其标准化,而不是试图解决当前的设计,您会从中受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM