我正在制作一个AirBnb副本,我正在尝试创建一个仅返回赞助房屋的api。
DB表
我写的查询不能找到任何房子,你能帮我找到错误吗?谢谢你!
$houses = House::with(['position', 'user', 'messages', 'services', 'visualizations', 'sponsorships'])
->whereHas('sponsorships', function($query) {
$query->whereTime('sponsor_start', '<=', Carbon::now())
->whereTime('sponsor_end', '>', Carbon::now());
})
->where('is_visible','=', 1)
->paginate(12);;
sponsor_start
和sponsor_end
是透视表中的列
假设你的关系定义如下:
//Sponsorship model
public function houses()
{
return $this->belongsToMany(House::class)
->withPivot('sponsorship_start', 'sponsorship_end')
->withTimestamps();
}
//House model
public function sponsorships()
{
return $this->belongsToMany(Sponsorship::class)
->withPivot('sponsorship_start', 'sponsorship_end')
->withTimestamps();
}
您可以尝试以下操作-通过数据透视表名称
限定数据透视表的列$houses = House::with(['position', 'user', 'messages', 'services', 'visualizations', 'sponsorships'])
->whereHas('sponsorships', function($query) {
$query->whereTime('house_sponsorship.sponsor_start', '<=', Carbon::now())
->whereTime('house_sponsorship.sponsor_end', '>', Carbon::now());
})
->where('is_visible','=', 1)
->paginate(12);;