Laravel HasManyThrough 在这种情况下不起作用怎么办?
Laravel HasManyThrough doesn't work in this situation how to do it?
我有3个模型
用户
- id
活动
- id
- end_time
EventUser(这代表通过评论加入活动的用户)
- user_id
- event_id
- 评论
我们想做$user->events
(列出用户已加入的所有活动的活动详情)
但是,如您所见,中间 table 是一个枢轴 table... 因此事件 table 不引用它(这是hasManyThrough 函数)。
例如,我可能想要获取用户已加入且已 结束的所有事件的事件 详细信息 。
现在我在用户模型中这样做
private function eventQuery() {
return Event::join('event_user', 'events.id', '=', 'event_user.event_id')
->where('user_id', $this->id); // event_user.user_id
}
public function events() {
return $this->eventQuery()->get();
}
public function pastEvents() {
return $this->eventQuery()
->where('end_time', '<', new \DateTime()) // events.end_time
->get();
}
但是在这种情况下有没有像 hasManyThrough 这样的 laravel 方法呢?
laravel方法是:
用户模型:
public function events()
{
return $this->belongsToMany('App\Event')->withPivot('comment');
}
事件模型:
public function users()
{
return $this->belongsToMany('App\User')->withPivot('comment');
}
当您拨打电话时:
$user = App\User::whereId($id)->where('end_time','<=',$now)->with('events')->get();
事件关系将根据您希望的方式通过数据透视表 table 的注释字段进行检索。
我有3个模型
用户
- id
活动
- id
- end_time
EventUser(这代表通过评论加入活动的用户)
- user_id
- event_id
- 评论
我们想做$user->events
(列出用户已加入的所有活动的活动详情)
但是,如您所见,中间 table 是一个枢轴 table... 因此事件 table 不引用它(这是hasManyThrough 函数)。
例如,我可能想要获取用户已加入且已 结束的所有事件的事件 详细信息 。
现在我在用户模型中这样做
private function eventQuery() {
return Event::join('event_user', 'events.id', '=', 'event_user.event_id')
->where('user_id', $this->id); // event_user.user_id
}
public function events() {
return $this->eventQuery()->get();
}
public function pastEvents() {
return $this->eventQuery()
->where('end_time', '<', new \DateTime()) // events.end_time
->get();
}
但是在这种情况下有没有像 hasManyThrough 这样的 laravel 方法呢?
laravel方法是:
用户模型:
public function events()
{
return $this->belongsToMany('App\Event')->withPivot('comment');
}
事件模型:
public function users()
{
return $this->belongsToMany('App\User')->withPivot('comment');
}
当您拨打电话时:
$user = App\User::whereId($id)->where('end_time','<=',$now)->with('events')->get();
事件关系将根据您希望的方式通过数据透视表 table 的注释字段进行检索。