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

问题描述 投票:4回答:2

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

Table tours

id | name | country_id | featured

Table countries

id | name

Pivot Table country_tour

id | country_id | tour_id

我想找到将featured列的旅游表设置为1并且country_idcountry_tour表设置为1的旅游。

php laravel laravel-5.3
2个回答
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 = 1country with id = 1之旅的集合。

希望这可以帮助!


0
投票

参考Saumya Rastogi的答案,将id更改为countries.id以避免where子句中的“column'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();
© www.soinside.com 2019 - 2024. All rights reserved.