How to query by Eloquent ORM value? Let's make it quick,
I have two models:
with a one-to-one relationship.
I can perform such relationship actions like:
UserBalance::find(1)->user->name; // returns name
Now I want to perform a query, but now I am confused! What I want to do:
UserBalance::with(['user'])->where( ... ) // here I am confused
/**
* What I wanna do: where()->user->isActive()
* note: isActive() is a public function on User model
* which performs some other actions.
**/
With can take a function :)
UserBalance::with(['user' => function($query) {
$query->where('active', 1); //or some other query on the users table
}])->get();
But most likely you are actually after whereHas (to filter UserBalance) As it is one to one, the with does not need any query :)
UserBalance::with('user')->whereHas('user', function($query) {
$query->where('active', 1); //or some other query on the users table
})->get();
You can also save closure to the variable, if it's same.
UserBalance::with(['user' => $closure = function($query) {
$query->where('active', true);
}])->whereHas('user', $closure)->get();
Please sign in or create an account to participate in this conversation.