Eloquent 关系 Laravel ManytoMany 通过
Eloquent Relationship in Laravel ManytoMany Through
我的 Laravel 项目中有三个 类:City、Company 和 activity。所以,City有很多Company,Company属于一个city;然后我知道那家公司可能有一项或多项活动;我想问的是如何在一个城市进行所有活动。
城市模式:
public function companies()
{
return $this->hasMany('App\Models\Company');
}
公司型号:
public function city()
{
return $this->belongsTo('App\Models\City');
}
public function activities()
{
return $this->belongsToMany('App\Models\Activity');
}
Activity 型号:
public function companies()
{
return $this->belongsToMany('App\Models\Company');
}
谢谢你所做的一切。
最好的问候。
您可以使用 nested eager loading:
加载包含所有公司和活动的城市模型
City::with('companies.activities')->find($cityId);
如果只想加载活动,可以使用whereHas()
方法:
Activity::whereHas('companies', function($q) use($cityId) {
$q->where('city_id', $cityId);
})->get();
我的 Laravel 项目中有三个 类:City、Company 和 activity。所以,City有很多Company,Company属于一个city;然后我知道那家公司可能有一项或多项活动;我想问的是如何在一个城市进行所有活动。
城市模式:
public function companies()
{
return $this->hasMany('App\Models\Company');
}
公司型号:
public function city()
{
return $this->belongsTo('App\Models\City');
}
public function activities()
{
return $this->belongsToMany('App\Models\Activity');
}
Activity 型号:
public function companies()
{
return $this->belongsToMany('App\Models\Company');
}
谢谢你所做的一切。 最好的问候。
您可以使用 nested eager loading:
加载包含所有公司和活动的城市模型City::with('companies.activities')->find($cityId);
如果只想加载活动,可以使用whereHas()
方法:
Activity::whereHas('companies', function($q) use($cityId) {
$q->where('city_id', $cityId);
})->get();