【问题标题】:Retrieve all models that are not associated with another model through pivot通过 pivot 检索所有与另一个模型不关联的模型
【发布时间】:2017-05-16 11:31:03
【问题描述】:

我有三个表:usersorganizationsorganization_userorganization_userusersorganizations 之间多对多关系的数据透视表。对应的模型中已经正确设置了多对多关系。

我需要获取与给定组织无关的所有用户。这应该如何使用 eloquent 来完成。以下是我尝试过的,但没有返回任何结果:

public function associate_user($organization_id){

        $data = [
            'organization'      => \App\Organization::find($organization_id),
            'users'             => \App\User::whereDoesntHave('organizations', function($query) use ($organization_id){
                $query->where('organization_id', $organization_id);
            })
        ];

        return view('admin.associateUser', $data);

    }

【问题讨论】:

  • 你在whereDoesntHave之后忘记了->get();
  • 0_0...哇...我想是时候收工了。谢谢@DanMiller

标签: php laravel eloquent


【解决方案1】:

您永远不会真正执行查询。

您需要在查询生成器的末尾调用get()

public function associate_user($organization_id) {
    $data = [
        'organization' => \App\Organization::find($organization_id),
        'users'        => \App\User::whereDoesntHave('organizations', function($query) use ($organization_id){
            $query->where('organization_id', $organization_id);
        })->get(); // Add the call to get()
    ];
    return view('admin.associateUser', data);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多