【问题标题】:Laravel Relations - Many to oneLaravel 关系 - 多对一
【发布时间】:2020-10-07 13:33:27
【问题描述】:

在索引页面上,我想显示最后 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 }}

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

【问题讨论】:

    标签: laravel foreign-keys


    【解决方案1】:

    如果您的事件表有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 关系

    【讨论】:

    • 工作感谢!但我认为你是对的。将重建以使用额外的表
    • 很高兴为您提供帮助 :) 编码愉快。
    猜你喜欢
    • 2018-06-15
    • 2018-09-27
    • 2017-12-24
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多