如何在Laravel中使用模型进行操作?

时间:2016-10-11 02:14:52

标签: php laravel

所以我有这种情况,如果用户在members()模型中,我需要根据登录用户过滤项目列表。

public function index(Request $request = null, $search = null)
{
    $user = $this->user;
    $data = project_registry::with('members', 'members.profile')->where('isdelete', 0);

    if(!$user->project_view) {
        // here i need to do the filter for the login user to view project where they are the member of the project
    }

    if(!is_null($request['search'])) {
        $search = $request['search'];
        $data->where(function($q) use ($search) {
            $q->where('Project_Code', 'LIKE', "%$search%")->orWhere('Project_Short_name', 'LIKE', "%$search%");
        });
    }

    $data = $data->orderBy('Project_ID')->paginate(20);

    return view('project.index', compact('data', 'search'));
}

1 个答案:

答案 0 :(得分:0)

使用wherehas

project_registry::whereHas('members', function($q) use ($user) {
    $q->where('user_id', $user->id);
})->...