duanqian8867 2018-11-21 16:57
浏览 62

Laravel Query构建器中的多对多关系

Let's consider that I have a model called Sportman and another one Sport who are linked via a pivot table : many to many relationship.

A sample code for their migrations.

# 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');
});

Here is their relationship in models :

# 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 );
}

How can I using Laravel with Eloquent get the sportsman that play:

  1. Only "Footbal"
  2. Box or "Swimming"
  3. Both "Tennis and Basket-ball

Here is what I tried to do for question 2 :

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

Most difficult is the question 3

  • 写回答

1条回答 默认 最新

  • douyou2732 2018-11-21 18:35
    关注

    You put a subquery on whereHas function...

    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();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'