John Davidson

php - laravel where condition for related eloquent

0 comments
Message:


I have to Models User and UserAttr


User is like :




















id name
1 john
2 doe


My Answer:
UserAttr is like:




id
user_id
attr_name
attr_value




1
1
age
25


2
1
gender
male


3
2
age
30


4
2
gender
female



Now, I want to get all users whose age is greater than 25. I can achieve this using Laravel Eloquent whereHas method.

Here is the code snippet:

php
$users = User::whereHas('userAttr', function($query) {
$query->where('attr_name', 'age')
->where('attr_value', '>', 25);
})->get();


This code will fetch all users whose age is greater than 25.

Rate this post

3 of 5 based on 4282 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us