在查询中使用连接时无法访问相关模型 - Laravel

时间:2015-04-15 03:40:21

标签: php laravel

我尝试按状态过滤代理商模型。状态列位于单独的模型上,即用户。所以在我的存储库中,我就是这样做的:

public function blocked($howMany = 10)
{
    return $this->model->join('users', 'users.userable_id', '=', 'agents.id')
            ->where(function($query)
            {
                $query->where('users.status', config('user.status.blocked'));
            })
            ->paginate($howMany);
}

$ this-> model 的值是构造函数中注入的代理模型实例。现在,这段代码可以在我的控制器循环中运行:

public function blocked()
{
    $agents = $this->agents->blocked();

    foreach ($agents as $agent)
    {
        dd($agent->user);
    }

    return view('agents.admin', compact('agents'));
}

用户的值为空。这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

通常你的关系如下:

public function blocked($howMany = 10)
{
    return $this->hasMany('users', 'userable_id', 'id')
                ->where('status','=',config('user.status.blocked'))
                ->paginate($howMany);
}

来源:http://laravel.com/docs/4.2/eloquent#one-to-many