Laravel 5 雄辩的 whereIn

Laravel 5 eloquent whereIn(Laravel 5 雄辩的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)