Laravelian eloquent search in the fields of a related model

I have eloquent models such as

User : users (identifier, username, password, email address, status)

Profile : profiles (id, user_id, first_name, last_name, gender, dob)

In the controller logic, I look forward to loading the profile model.

I can do it,

$user = User::with('Profile')->get(); 

or

 $user = User::with('Profile')->where('status', '1')->get(); 

but how to do something like

 $user = User::with('Profile')->where('status', '1')->where('gender', 'Male')->get(); 
+6
source share
2 answers

What whereHas come in handy:

 $user = User::with('Profile')->where('status', 1)->whereHas('Profile', function($q){ $q->where('gender', 'Male'); })->get(); 

This basically adds the condition that the user must have a profile with gender = Male

+21
source

If you want to find multiple columns in a relationship model.

  $searchText = 'test text'; Product::with('owner')->where(function($query) use ($searchText) { $query->where('product_name', 'LIKE', '%' . $searchText . '%'); $columns = ['product_code', 'place_location', 'remark']; foreach ($columns as $column ) { $query->orWhere($column, 'LIKE', '%' . $searchText . '%'); } $query->orWhereHas('owner', function($q) use ($searchText) { $q->where(function($q) use ($searchText) { $q->where('name', 'LIKE', '%' . $searchText . '%'); $q->orWhere('company_name', 'LIKE', '%' . $searchText . '%'); }); }); }); 
+1
source

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


All Articles