Laravel 5 eloquent whereIn(Laravel 5 雄辩的 whereIn)
问题描述
希望有人能帮助我,我需要在数据库中搜索类别 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 5 雄辩的 whereIn
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
