我在时间段和房间之间建立了多对一的关系,如下所示:
房间类
class room extends Model
{
function timeslot()
{
return $this->hasMany(timeslot::class);
}
}
时段类
class timeslot extends Model
{
function room()
{
return $this->belongsTo(room::class,'room_id','id');
}
}
我想急切加载所有时段及其相应的房间。我正在使用:
App\timeslot::with('room')->get()
但是,如果两个时隙使用一个房间,则仅加载房间的第一个实例。我想要的是在每个时间段的实例中包含房间的全部细节。这是我得到的输出:
Illuminate\Database\Eloquent\Collection {#866
all: [
App\timeslot {#859
id: 1,
slot-count: 1,
created_at: "2018-02-25 07:30:02",
updated_at: "2018-02-25 07:30:02",
day_id: 1,
group_id: null,
room_id: null,
room: null,
},
App\timeslot {#858
id: 2,
slot-count: 2,
created_at: "2018-02-25 07:30:02",
updated_at: "2018-02-25 07:30:02",
day_id: 1,
group_id: null,
room_id: null,
room: null,
},
App\timeslot {#857
id: 3,
slot-count: 3,
created_at: "2018-02-25 07:30:02",
updated_at: "2018-02-25 07:30:02",
day_id: 1,
group_id: 2,
room_id: 1,
room: App\room {#870
id: 1,
name: "A108",
created_at: "2018-02-25 07:30:02",
updated_at: "2018-02-25 07:30:02",
},
},
App\timeslot {#856
id: 4,
slot-count: 4,
created_at: "2018-02-25 07:30:02",
updated_at: "2018-02-25 07:30:02",
day_id: 1,
group_id: 3,
room_id: 1,
room: App\room {#870},
},
],
}
这可能不是错误,而是一个功能!
有没有办法修改查询(我已经简化了它,因为我也希望获得组 - 但会对两者应用相同的解决方案)以重复每个实例的房间信息?