带有数据透视表的Laravel查询构建器

时间:2016-11-17 16:07:39

标签: php laravel laravel-5.3

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

tours

id | name | country_id | featured

countries

id | name

数据透视表country_tour

id | country_id | tour_id

我想查找将featured列的旅程表设置为1并将country_id country_tour表设置为1的旅程。

2 个答案:

答案 0 :(得分:4)

<强>更新:

你可以使用Laravel的查询构建器方法 - whereHas()

这样做

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

游览模式:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

和国家/地区模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

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

这将为您提供featured = 1并拥有country with id = 1的旅行集合。

希望这有帮助!

答案 1 :(得分:0)

关于Saumya Rastogi的答案,请将id更改为country.id,以避免出现“ where子句不明确的列'id'”错误。

发件人:

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

收件人:

Tour::where('featured', 1)
->whereHas('countries', function($q) {
    $q->where('countries.id', 1);
})->get();