laravel - Laravel 关系 - 多对一
问题描述
在索引页面上,我想显示最后 10 个事件。每个事件有 4 名参与者(称为用户)。
事件表示例:
id, name, user_one, user_two, user_three, user_four, event_start_time, more_event_data...
在控制器中,我将事件数据发送到视图:
public function index()
{
if( !AuthUserHasPermissionToRoute( 'event.index' ) )
abort( 404 );
return view( 'event.index' )
->with('event', Event::orderBy('id', 'DESC')->get() );
}
使用模型我也想发送用户数据
在 EventModel 中,我尝试过 hasMany(但只会使用 1 个)
public function users()
{
return $this->hasMany( User::class, 'id', 'user_one', 'id' );
}
和多对多:
public function users()
{
return $this->belongsToMany( User::class );
}
在视图中,我试图让用户名(以后可能更多)被显示
{{ $game->users->user_one->name }}
{{ $game->users->user_two->name }}
{{ $game->users->user_three->name }}
{{ $game->users->user_four->name }}
但我无法让它工作,有人可以告诉我我做错了什么吗?
解决方案
如果您的事件表有user_one, user_two, user_three, user_four
用户 ID,那么对于事件表,关系应该是belongsTo
事件模型
public function user_one()
{
return $this->belongsTo( User::class,'user_one', 'id');
}
public function user_two()
{
return $this->belongsTo( User::class,'user_two', 'id');
}
public function user_three()
{
return $this->belongsTo( User::class,'user_three', 'id');
}
public function user_four()
{
return $this->belongsTo( User::class,'user_four', 'id');
}
我建议制作一张不同的桌子user_events
并belongsToMany
与之建立关系
推荐阅读
- mysql - 如果匹配,则合并连续的行
- asp.net-core - .NET 6 RC1 和 VS2022 预览版中的 Blazor wasm 托管应用程序 4 返回未找到
- macos - 在设置中更改磁盘映像位置后,Docker 容器和映像在 OSX 上不再可见
- python - 将屏幕过渡方向应用于扩展面板和屏幕 kivy/kivymd 内的元素卡
- gitlab - Gitlab - 从问题创建分支和合并请求
- sqlite - 这两个 SQLite 查询会产生相同的结果吗?
- variables - 如何将 ColdFusion cfoutput 查询行#/ID 传递给另一个 CFM 或函数?
- ios - 使用苹果登录在模拟器中使用 swift 不起作用
- macos - 需要在mac上安装Watchman 4.9.0版本
- java - 如何阻止我的代码重复菜单打印?