【问题标题】:Laravel Query Builder - whereHas with query select valueLaravel 查询生成器 - whereHas 带有查询选择值
【发布时间】:2018-06-05 18:05:02
【问题描述】:

我很困惑 whereHas 函数是如何工作的?

我想从主查询中检查 whereHas 中的一列。

ClientSeatController.php

$seats = ClientSeat::where('clientId',$req->clientId)
          ->wherehas('services',function($query) use($req){
            $query->where('clientId',$req->clientId);
          })->get(); 

ClientSeat.php(关系)

public function services(){
    return $this->hasOne(ClientSeatService::class,'clientSeatId','clientSeatId');
}

toSql();

select * from `sln_client_seats` where `clientId` = 3 and exists (select * from `sln_client_seat_services` where `sln_client_seats`.`clientSeatId` = `sln_client_seat_services`.`clientSeatId` and `clientId` = 3)

我需要如下查询。

select * from `sln_client_seats` where `clientId` = 3 and exists (select * from `sln_client_seat_services` where `sln_client_seat_services`.`clientSeatId` =`sln_client_seats`.`clientSeatId`  and `clientId` = 3)

我想检查 client_seat_services 表的 clientSeatId 与 whereHas 函数内的 client_seats 表列的 clientSeatId。

查询未按预期正确执行。

请帮帮我。

【问题讨论】:

  • 它是否抛出任何错误?
  • 没有得到任何错误,得到空结果。我想从表中得到 3 行。

标签: laravel eloquent laravel-5.6


【解决方案1】:

从whereHas 闭包中删除$query->where('clientSeatId','client_seats.clientSeatId');。您的 ClientSeat::services() 方法已经定义了关系的那一部分。您在那里编写它的方式实际上是将字符串“client_seats.clientSeatId”放在查询中,而不是实际的 Id 值。所以你不会得到错误,所有的结果都是空的。

【讨论】:

  • 当我根据您的评论删除代码时,我会收到更新问题中的查询。其实是错的。存在查询的 where 子句检查错误。 sln_client_seats.clientSeatId = sln_client_seat_services.clientSeatId
  • 该查询现在与“我需要如下查询”中的查询匹配。只是换了边,但这无关紧要。
猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 2021-01-01
  • 2017-09-12
  • 2015-05-09
相关资源
最近更新 更多