問題描述
希望有人能幫助我,我需要在數據庫中搜索類別 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!