【问题标题】:Eloquent Nested relations with where clause query returns collection on false condition雄辩的嵌套关系与 where 子句查询在错误条件下返回集合
【发布时间】:2018-03-05 14:40:23
【问题描述】:

我正在尝试搜索所有具有 RentItem 的 RentItem,其书名与给定的 $input 类似。

问题是当输入不匹配时,我仍然得到一个集合返回。 唯一的区别是 book 关系是 null 而不是集合。

应该返回 false 的查询结果: https://pastebin.com/pd7UqhCi

查询结果为真: https://pastebin.com/shndvdMh

当 book 等于 null 时,我不希望返回 Rent 模型。

我的查询

$rents = Rent::with(['rentItems.book' => function ($query) use ($input) { 
       $query->where('books.title', 'LIKE', "%$input%"); 
}])->get();

租模关系

public function rentItems()
{
  return $this->hasMany(RentItem::class);
}

RentItems 模型关系

public function book()
{
     return $this->belongsTo(Book::class);
}

public function rent()
{
     return $this->belongsTo(Rent::class);
}

我做过的研究:

【问题讨论】:

    标签: php laravel collections nested-queries


    【解决方案1】:

    您需要使用whereHas() 方法。做这样的事情:

    $rents = Rent::whereHas('rentItems.book', function ($query) use ($input) { 
        $query->where('books.title', 'LIKE', "%$input%"); 
    })->get();
    

    【讨论】:

    • 非常感谢!像魅力一样工作。
    • 为什么不添加一个“with('rentItems.book')”,这并不急于加载。实际上不确定操作是否想要那个
    • OP 不想急切加载。他想按关系过滤Rent 记录。
    • @AlexeyMezenin 如果以下查询中有任何错误,您能帮我吗?出勤::with(['teacher:EMPID,EMPNAME,EMAIL,MOBILENO,SCHOOLID,DESIGNATION', 'classs:SID,CLASSNAME,SCHOOLID', 'attendanceAbsent.student', 'attendanceAbsent.leave'])->whereDate(' created_at', $request->date)->whereHas("attendanceAbsent", function($q) use($request) { $q->where("attendance_id", "=", $request->id); } )->whereHas('attendanceAbsent.leave', function ($query) { $query->whereDate('created_at', Carbon::today()); })->first()
    猜你喜欢
    • 2021-05-29
    • 2016-09-18
    • 2018-12-09
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 2020-09-29
    相关资源
    最近更新 更多