[英]Laravel Eloquent hasMany\hasOne limit parents to children with records
[英]Laravel Eloquent HasMany / HasOne Additional On Clauses
早上好,
道歉,如果以前曾有人問過這個問題,但我們無法找到所遇到問題的任何答案。
我們正在使用一個不屬於我們的舊數據庫(只讀),並且正在嘗試使用Laravel中的Eloquent(模型)來解決一些常見問題。
是否可以設置Eloquent的Eager-loading來為HasMany / HasOne關系構建器創建其他ON子句?
請在下面看到我們在沒有原始查詢的情況下要實現的目標。
public function policy()
{
return $this->hasMany(Policy::class, 'Group', 'Group')
// This breaks as `on` isn't defined on Eloquent\Builder. Is this concept possible? Multiple on clauses
->on('Reference', 'Reference');
}
在我們的控制器中,我們嘗試了以下操作,但也失敗了。
Vehicle::with([
'policy' => function ($query) {
// Model isn't instantiated yet, but we need an additional on clause here
$query->on('Reference', 'Reference');
}
]);
可以實現上述目標嗎?還是必須恢復使用原始查詢?
預先感謝您的任何幫助。
您可以使用Compoships
軟件包:
class Vehicle extends Model
{
use \Awobaz\Compoships\Compoships;
public function policy()
{
return $this->hasMany(Policy::class, ['Group', 'Reference'], ['Group', 'Reference']);
}
}
我假設查詢已經作為原始SQL存在,而您想要實現的是將其轉換為雄辯的。 如果是這種情況,您可能會發現使用內置的原始查詢會更快一些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.