我有两个带有数据透视表的表
tours
id | name | country_id | featured
countries
id | name
country_tour
id | country_id | tour_id
我想查找将featured
列的旅程表设置为1并将country_id
country_tour
表设置为1的旅程。
答案 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();