【问题标题】:How to eagerload an array of values from a belongsTo relationship如何从 belongsTo 关系中预先加载一组值
【发布时间】:2015-10-14 06:37:20
【问题描述】:

我有 3 个表代表 UserGroupGroupUser 之间的多对多(属于多多)关系作为数据透视表。我想做的只是显示所有不是group_id 2成员的用户。

User model    GroupUser model (pivot table)      Group model

ID|name         ID|user_id|group_id            ID|group_name
1 |Mark          1| 1     |2                    1| the sharks
2 |Sam           2| 3     |1                    2| the tigers
3 |Sally         3| 2     |3                    3| the whales
4 |Tim           4| 4     |2 

我的解决方案 在 User 和 GroupUser 之间创建 belongsTo (hasMany) 关系,以便 GroupUser belongsTo User 然后立即加载所有不是 group_id 2 成员的用户。

如何在控制器中编写代码并在刀片中查看?

在我使用 WhereNotIn 条件之前,我试图简单地预先加载所有用户。到目前为止,我有这个,但由于某种原因,它只读取 group_user 表中的最后一行。

     foreach (GroupUser::with('belongstomethod')->get() as $query)
{
     $query->belongstomethod->name;
}

上面代码的结果是 Tim

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    这将显示所有不属于 group_id = 2 的用户。

    控制器或存储库:

    $group_id = 2;
    $users = User::whereHas('groups',function($query) use($group_id) {
        $query->where('id','!=',$group_id); 
    })->get();
    
    return view('your_view',compact('users')); //this will pass the $users collection to the view.
    

    查看(使用刀片):

    @foreach($users as $user)
        {{$user->name}}
        {{$user->etc}}
    @endforeach
    
    • 此代码假定您的用户模型上有一个名为“组”的公共方法。并且该方法返回一个 belongsToMany 关系。

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多