繁体   English   中英

Laravel 7 - 在数据透视表上查询条件

[英]Laravel 7 - query with conditions on pivot table

我正在制作一个 AirBnb 副本,我正在尝试创建一个仅返回赞助房屋的 api。

数据库表

我写的查询找不到任何房子,你能帮我找出错误吗? 谢谢!

$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_startsponsor_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);;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM