繁体   English   中英

使用多个 where 子句在单个 Eloquent Laravel 中连接 2 个表

[英]Join 2 tables in a Single Eloquent Laravel using multiple where clause

在这里,我想找到解决方案来简化我的查询,以便在 Laravel 中使用 eloquent 获取数据。

$room_id = Booking::whereBetween('from', [$request->from, $request->to])
                     ->orWhereBetween('to', [$request->from, $request->to])
                     ->where('from', '<=', $request->from, )
                     ->where('to', '>=', $request->from)
                     ->pluck('room_id');
                     
$rooms = Room::whereNotIn('id', $room_id )->get();

所以在这里我有 2 个 Eloquent 操作来获取未包含在具有指定要求的预订表中的房间。 到目前为止,我对此没有任何问题,但是你们能给我最好的做法来简化我的工作吗? 谢谢你。

确保“预订”关系写在您的房间模型上。

$rooms = Room::whereDoesntHave('bookings', use($request) function($q){ 
    $q->whereBetween('from', [$request->from, $request->to])
    $q->orWhereBetween('to', [$request->from, $request->to])
    $q->where('from', '<=', $request->from, )
    $q->where('to', '>=', $request->from)
})->get();
  • 您可以参考 laravel 关系将其添加到模型中,然后使用 whereHas 查询连接表: https ://laravel.com/docs/9.x/eloquent-relationships

例子:

  • 有选项

受保护的 $with = ['product_savour'];

  • 关系

公共函数 product_savour() { return $this->hasMany(ProductSavour::class, 'product_id'); }

  • 询问
$productQuery->whereHas('product_savour', function ($query) use ($filters) { $query->whereHas('savour', function ($query) use ($filters) { $query->whereHas('type', function ($query) use ($filters) { $query->whereIn('id', $filters['savour']); }); }); });

暂无
暂无

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

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