繁体   English   中英

如何将 Eloquent where() 应用于 hasMany() 关系中的孩子

[英]How to apply Eloquent where() to child in hasMany() relationship

我想获得这个非常简单、常见的SELECT语句的结果:

SELECT * FROM parent
  JOIN child ON parent.id = child.parent_id
  WHERE child.column = 1;

对于非 SQL 流利者,这将返回所有父行和子行的所有列,其中名为column的子列包含值 1。

使用下面的 Laravel 模型,正确的 Eloquent 方法是什么?

<?php
class TheParent extends Model {
    public function child(): HasMany {
        return $this->hasMany(Child::class);
    }
}

class Child extends Model {
    public function parent(): BelongsTo {
        return $this->belongsTo(TheParent::class);
    }
}

// Fails.  Returns empty set.
$data = TheParent::getModel()
    ->child()
    ->where('column', 1)
    ->get();    // returns empty set

// Fails:  Returns correct data FOR JUST ONE parent Model if and only if a
// child meets the conditions. But find() is not usable for my purpose.
$data = TheParent::find(1)
    ->child()
    ->where('column', 1)
    ->get();

// Fails:  Only returns the parent data and cannot reference the child.
$data = TheParent::whereHas(
    'child',
    function ($query) {
        $query->where('column', 1);
    }
)->get();

您的最后一次尝试已接近尾声; 您的回调过滤返回的Parent实例,但不过滤附加的Child实例。 尝试这样的事情:

$data = TheParent::whereHas('child', fn($q) => $q->where('column', 1))
    ->with(['child' => fn($q) => $q->where('column', 1)])
    ->get();

必须为whereHaswith方法重复回调...

  • TheParent::with('child')返回所有带所有孩子的父母
  • TheParent::with(['child' => 'some condition'])返回所有有孩子的父母
  • TheParent::whereHas('child', 'some condition')返回一些带有所有孩子的父母
  • TheParent::whereHas('child', 'some condition')->with(['child' => 'some condition'])返回一些父母和一些孩子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM