让我们考虑一下,我有一个名为Sportman
的模型和另一个Sport
通过pivot
表链接的模型:多对多关系。>
有关其迁移的示例代码。
# Sportmans migration
Schema::create('sportsmans', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
});
# Sports migration
Schema::create('sports', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
});
以下是它们在模型中的关系:
# Defining association in Sportsman model
public function sports(){
return $this->belongsToMany( Sport::class, 'sportsman_has_sports', 'person_id', 'sport_id' );
}
# Defining association in Sports model
public function sportsman(){
return $this->belongsToMany( Sportsman::class );
}
我如何将Laravel与Eloquent结合使用来获得sportsman
的播放效果:
这是我为问题2尝试做的事情:
Sportsman::with(['sports:person_id,id,name'->whereHas('sports', function ($query) {
$query->whereIn('name', ['Box', 'Swimming'] );
});
最困难的是问题3
答案 0 :(得分:0)
您将子查询放在具有功能的地方...
Sportsman::whereHas('sports', function ($query) {
$query->whereIn('name', ['Box', 'Swimming'] );
})
->with('sports')
->get();
// Below is your last question
Sportsman::where(function ($query) {
$query->whereHas('sports', function ($subquery) {
$subquery->where('name', 'Tennis');
});
$query->whereHas('sports', function ($subquery) {
$subquery->where('name', 'Basket-ball');
});
})
->with('sports')
->get();