我有三个表:
品牌
-----------------
id | name | wheel
-----------------
轮子
-----------------------------
id |no_of_wheel | brand_wheel
-----------------------------
品牌轮
------------------------
id | brand_id | wheel_id
------------------------
我定义了以下模型:
class brand
{
public function brandWheel(){
return $this->hasMany(BrandWheel::class);
}
}
class BrandWheel
{
public function brand(){
return $this->belongsTo(Brand::class);
}
}
我想获取 wheel_id 为 2 的那些品牌。
我累了:
$brands = Brand::with(['brandWheel' => function($query){
$query->where('wheel_id','=',2);
}])->get();
此代码为我提供了表格中的所有品牌。有什么我想念的吗?
最佳答案
您应该使用whereHas
语句。 with
方法将预先加载给定的关系。您可以找到更多文档 here .
$brands = Brand::with('brandWheel')->whereHas('brandWheel', function($query) {
$query->where('wheel_id', 2);
})->get();
如果您只想要具有 brandWheel 关系的品牌,请使用 has
。结帐documentation有关更多信息。
关于php - 在两张 table 上 Eloquent Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53427300/