【问题标题】:Exclude items from a collection in Laravel从 Laravel 的集合中排除项目
【发布时间】:2015-07-12 17:29:01
【问题描述】:

在我的 Laravel 应用程序中,我有用户、朋友和组的概念。用户可以创建朋友并将其分类。

一个用户可以有很多朋友:

function friendsOfMine()
{
  return $this->belongsToMany('App\User', 'helpers', 'user_id', 'helper_id')
    ->wherePivot('accepted', '=', 1);
}

一个组可以有多个用户:

public function groupMembers()
{
    return $this->belongstoMany('App\User')->withTimestamps();
}

在将朋友添加到群组的 UI 中,我想显示用户朋友的完整列表,但排除那些已添加到群组的朋友。我的组控制器功能看起来像这样,虽然我很肯定我不在基地。

    public function add($id)
    {
    $group = Group::findOrFail($id);
    $helpers = $group->groupMembers;
    $id = $helpers->lists('id');
    $invitees = $this->user
        ->friendsOfMine()
        ->where('helper_id', '!=', $id)
        ->Paginate(5);
    return view('groups.add', compact('group','helpers','invitees'));
    }

理想情况下,我喜欢某种写作方式:

$helper = $group->friendsOfMine->not->groupMembers->Paginate(5);

是否可以使用来自两个不同模型的函数来过滤数据?

【问题讨论】:

    标签: php laravel eloquent laravel-5


    【解决方案1】:

    使用您的方法,您将不得不使用whereNotIn(),因为您有一个 id 数组:

    $id = $helpers->lists('id');
    $invitees = $this->user
        ->friendsOfMine()
        ->whereNotIn('helper_id', $id)
        ->Paginate(5);
    

    但是你可能也可以这样(假设关系group

    $invitees = $this->user
        ->friendsOfMine()
        ->whereDoesntHave('group', function($q) use ($id){
            $q->where('group_id', $id); // Note that id is the group id (not the array of ids from the helper)
        })
        ->Paginate(5);
    

    要获得更好的语法(如您的示例),您应该查看Query Scopes

    【讨论】:

    • 工作得非常好——感谢您的快速响应和添加的细节。查询范围正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多