【发布时间】:2021-10-29 07:26:41
【问题描述】:
我正在做一个 Laravel 项目,我有模型“预订”和“周”。
型号“Week”有开始日期和价格,型号“Reservation”有开始日期和结束日期。
我希望能够像这样做一个有说服力的选择:Reservation::with('weeks')->get(),但是如果我在 eloquent 以下做一些事情,就不会将其识别为关系,并且我不能在 Reservation 模型中使用“HasMany”,因为我不要将表格与 id 相关联,而仅与日期相关联。
我怎样才能获得一段关系的周数?
class Reservation extends Model
{
public function weeks()
{
return Week::whereDate('starting_date', '>=', $this->starting_date)
->whereDate('starting_date', '<', $this->ending_date)
->orderBy('starting_date')
->get();
}
}
已编辑:感谢@Tim Lewis
【问题讨论】:
-
Reservation::all()->with('weeks')不行;::all()转换为没有with()方法的 Collection。请改用Reservation::with('weeks')->get()。但是,如果你不能定义关系,那也行不通。您不能急于加载weeks(with('weeks')),因为它不会返回关系。
标签: php laravel eloquent relationship