我有两个带有数据透视表的表
tours
id | name | country_id | featured
countries
id | name
country_tour
id | country_id | tour_id
我想找到将featured
列的旅游表设置为1并且country_id
的country_tour
表设置为1的旅游。
更新:
你可以使用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
之旅的集合。
希望这可以帮助!
参考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();