多对多关系中的Laravel查询构建器

时间:2018-11-21 16:57:46

标签: php sql laravel laravel-5 eloquent

让我们考虑一下,我有一个名为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的播放效果:

  1. 仅“足球”
  2. Box 或“游泳”
  3. “网球和篮球

这是我为问题2尝试做的事情:

Sportsman::with(['sports:person_id,id,name'->whereHas('sports', function ($query) {
    $query->whereIn('name', ['Box', 'Swimming'] );
});

最困难的是问题3

1 个答案:

答案 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();