【问题标题】:JOINS with Many to Many Relationship - Laravel加入多对多关系 - Laravel
【发布时间】:2017-10-22 17:11:50
【问题描述】:

我有两个多对多关系表countries and teams table。在我的国家表中,有president_id。现在我想使用连接查询来获取属于该总统 ID 的团队,但我无法实现这一点。

我如何才能选择属于特定总裁的所有团队?

PS:新手用 laravel

国家

public function teams()
    {
        return $this->belongsToMany('App\Team');
        ->withTimestamps();
    }

团队

public function countries()
    {
        return $this->belongsToMany('App\Country')
        ->withTimestamps();
    }

控制器

$teams = Team::all()->with('countries')->where('president_id,1)->first();
$getTeams =  $teams->pluck('id')->toArray();

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你可以得到所有拥有一些president_id的国家的团队,如下所示:

    $president_id = 1;
    $teams = Team::whereHas('countries',function($q)use($president_id){
                 $q->where('president_id',$president_id);
             })->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 2018-01-22
      • 2016-02-26
      • 2016-01-04
      • 2018-07-04
      相关资源
      最近更新 更多