我是 Laravel 和 Eloquent 模型的新手,即使閱讀了檔案,我也發現很難理解最簡單的查詢。
我有兩個模型 Measure 和 MeasureType,我想選擇某種型別的所有度量。在 sql 中會是什么樣子:
select * from measures m
join measure_types mt on mt.id=m.measure_type_id
join measure_type_trans t on t.measure_type_id=mt.id
where t.name='xyz';
在測量中我有:
public function type()
{
return $this->belongsTo(MeasureType::class, 'measure_type_id');
}
在 MeasureType 中:
public function measures()
{
return $this->hasMany(Measure::class);
}
名稱列在可翻譯表中 measure_type_trans 我怎么做這樣簡單的查詢?
uj5u.com熱心網友回復:
如果您想要型別并在其中嵌套屬于它的度量
$measureType = MeasureType::where('name', 'xyz')->with('measures')->first();
//you can access the measures with the attribute having the same name as the relation
$measures = $measureType->measures;
如果您只想將度量作為一個集合(幾乎與您發布的查詢相同)
$measures = Measure::whereHas('type', function ($typeQueryBuilder) {
$typeQueryBuilder->where('name', 'xyz');
})->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/416428.html
標籤:
上一篇:找不到路線Laravel8
下一篇:在遷移時重構資料庫模式
