带有数据透视表的Laravel查询生成器

Zac*_*ale 6 php laravel laravel-5.3

我有两个带有数据透视表的表

tours

id | name | country_id | featured

countries

id | name

数据透视表 country_tour

id | country_id | tour_id

我想找到一个具有游featured旅行团表集的列1和country_idcountry_tour表设置为1。

Sau*_*ogi 6

更新:

您可以使用Laravel的query Builder方法-来做到这一点whereHas()

您的模型应如下所示(多对多关系):

旅游模式:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tour extends Model
{
    public function countries() {
      return $this->belongsToMany('App\Country');
    }
}
Run Code Online (Sandbox Code Playgroud)

和国家模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    public function tours() {
      return $this->belongsToMany('App\Tour');
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用以下查询获取所需的结果:

Tour::where('featured', 1)
    ->whereHas('countries', function($q) {
        $q->where('id', 1);
    })
    ->get();
Run Code Online (Sandbox Code Playgroud)

这将使您拥有featured = 1和拥有旅行团country with id = 1

希望这可以帮助!