首页 > 解决方案 > 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 }}

但我无法让它工作,有人可以告诉我我做错了什么吗?

标签: laravelforeign-keys

解决方案


如果您的事件表有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_eventsbelongsToMany与之建立关系


推荐阅读