Laravel eloquent relationship with and where is the article based on a foreign column

Hi, I want to get my projects stored in db, which belongs to auth user , which also creates clients (they have many projects and tasks) and tasks (belongs to the project and tasks and the user).

I want to get all tasks that are not marked as closed in the status table, I know that the identifier of this number is 2, and I can get this as such:

 public function getOpenProjects() { return \Project::with(['clients', 'tasks', 'status']) ->where('status_id', '!=', '2') ->whereUserId(Auth::user()->id) ->get(); } 

But how can I change this to query the column in the status table, i.e. in the name column in this table?

+5
source share
2 answers

You can try the following:

 $value = 'someName'; Project::with(['clients', 'tasks', 'status' => function($q) use($value) { // Query the name field in status table $q->where('name', '=', $value); // '=' is optional }]) ->where('status_id', '!=', '2') ->whereUserId(Auth::user()->id) ->get(); 

You can also try this (it will retrieve records only if query returns name , otherwise not):

 $value = 'someName'; Project::with(['clients', 'tasks', 'status']) ->whereHas('status', function($q) use($value) { // Query the name field in status table $q->where('name', '=', $value); // '=' is optional }) ->where('status_id', '!=', '2') ->whereUserId(Auth::user()->id) ->get(); 
+16
source

You can try the following:

 Project::with(['clients', 'tasks' => function($q) use($value) { // Query the name field in status table $q->where('status_id', '!=', '2'); }]) ->whereUserId(Auth::user()->id) ->get(); 
0
source

Source: https://habr.com/ru/post/1202381/


All Articles