更新时间:2022-06-02 08:47:49
已更新:
您可以使用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
.
希望这会有所帮助!