或者不使用Laravel的有说服力的关系查询

时间:2021-10-09 18:53:11

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


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.

这就是你需要的。