我想得到這個非常簡單、常見的SELECT陳述句的結果:
SELECT * FROM parent
JOIN child ON parent.id = child.parent_id
WHERE child.column = 1;
對于非 SQL fluent,這將回傳所有父行和子行的所有列,其中名為的子列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();
uj5u.com熱心網友回復:
你最后一次嘗試很接近;您的回呼過濾Parent回傳的實體,但不過濾附加的Child實體。嘗試這樣的事情:
$data = TheParent::whereHas('child', fn($q) => $q->where('column', 1))
->with(['child' => fn($q) => $q->where('column', 1)])
->get();
必須為whereHas和with方法重復回呼...
TheParent::with('child')回傳所有孩子的所有父母TheParent::with(['child' => 'some condition'])回傳所有帶有一些孩子的父母TheParent::whereHas('child', 'some condition')回傳一些帶有所有孩子的父母TheParent::whereHas('child', 'some condition')->with(['child' => 'some condition'])回傳一些帶有一些孩子的父母。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/468404.html
上一篇:在GO中決議多維陣列
下一篇:PHP例外類中的反向級聯?
