In Laravel, I have two tables named Booking and Clients. For a specific booking, I have belongsTo relation with a single Client. Everything works well when I query a client for a booking except when I include orWhere. Please look at the code snippet below.

在Laravel,我有两张桌子叫Booking and Clients。对于特定的预订,我与一个客户有关系。当我向客户查询预订时,一切都运行得很好,除了包括或在哪里。请查看下面的代码片段。

if($client_name!=null)
        {
            $client_name='%'.$client_name;
            $bookings=$bookings->whereHas('client',function($q) use ($client_name){
                $q->where('first_name','LIKE',$client_name)
                    //->orWhere('last_name','LIKE',$client_name);                 
            });
        }

With the commented out orWhere line, I get proper bookings with the client with first_name as specified by user. But when I use or in the query for last_name, all the rows are displayed as if last_name matched for every row.

有了注释出来的或where行,我就可以用用户指定的first_name与客户进行适当的预订。但是当我使用或在查询last_name时,所有的行都会显示出来,好像每一行都匹配last_name。

What's wrong with it? Help please.

有什么问题吗?请帮助。

1 个解决方案

#1


9

The problem is that you have such code now:

问题是你现在有这样的代码:

WHERE foreignKey = X AND first_name = Y OR last_name = Z

So obviously it's not returning what it should.

很明显,它没有返回它应该返回的值。

Now, to make it work, you need to add those constraints as a sub where:

现在,为了让它起作用,你需要把这些约束添加到下面:

$bookings=$bookings->whereHas('client',function($q) use ($client_name){
            $q->where( function ($q) use ($client_name) {
                $q->where('first_name','LIKE',$client_name)
                    ->orWhere('last_name','LIKE',$client_name);
            });
        });

This will result in a query like:

这将导致如下查询:

WHERE foreignKey = X AND (first_name = Y OR last_name = Z)

which is what you need.

这就是你需要的。

更多相关文章

  1. php mail函数一段好的代码
  2. 用于上传多个文件的PHP代码
  3. (phpQuery)对网站产品信息采集代码的优化
  4. 韩顺平_php从入门到精通_视频教程_学习笔记_源代码图解_PPT文档
  5. 【MySQL 技巧分享】 mysql -e 加 v 简化代码
  6. Oracle相当于MySQL代码“插入虚拟”以返回错误消息
  7. 登录使用PHP并´t显示任何html代码
  8. 如何使用本地phmyadmin客户端访问远程服务器?
  9. MySQL客户端输出窗口显示中文乱码问题解决办法

随机推荐

  1. PHP闭包function() use()中的详细使用方
  2. PHP传递数组格式参数到shell脚本中
  3. php主要是干什么用的
  4. php-resque :基于Redis的后台任务系统
  5. 解析PHP的self关键字
  6. php网站怎么做
  7. phpcms如何修改成手机pc自适应
  8. 如何对php文件加密
  9. 使用 phpdbg 来调试php程序
  10. phpcms如何制作模板