带有数据透视表的Laravel查询生成器 [英] Laravel query builder with pivot table
问题描述
我有两个带有数据透视表的表
I have two tables with a pivot table
id |名称|country_id |特色
id |名称
id |country_id |tour_id
我想找到游览表的 features
列设置为1,而 country_tour
表的 country_id
设置为1的游览.
I want to to find the tour that has featured
column of tours table set to 1 and country_id
of country_tour
table set to 1.
推荐答案
已更新:
您可以使用Laravel的查询生成器方法来做到这一点- whereHas()
:
You can do it like this using Laravel's query Builder method - whereHas()
:
您的模型应如下所示(多对多关系):
Your models should look like this (Many to Many Relationships):
游览模型:
<?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');
}
}
,现在您可以使用以下查询获取所需的结果:
and now you can fetch the desired results by using the below query:
Tour::where('featured', 1)
->whereHas('countries', function($q) {
$q->where('id', 1);
})
->get();
这将为您提供具有 featured = 1
且具有 id = 1
的国家/地区的旅行团.
This will get you the collection of tours with featured = 1
and having country with id = 1
.
希望这会有所帮助!
这篇关于带有数据透视表的Laravel查询生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!