Reputation: 139
I have a model stored in a variable like:
$user = User::where('name', 'like', $test)
->orderBy('name');
I would like to build another query where I can join $user
. Can't find the right syntax to do it.
What am trying to achieve:
$numbers= Number::join($user, $users.id, '=', 'number.user_id')
->where('name', 'like', "%" . $validated['text'] . "%")])
->get();
Upvotes: 0
Views: 216
Reputation: 1554
Join can be written in this way
$records = User::select('users.*')
->where('users.name', 'like', $test)
->join('numbers', function($join) {
$join->on('users.id', '=', 'numbers.id')
->where('numbers.name', 'like', "%" . $validated['text'] . "%");
})
->get();
Upvotes: 0
Reputation: 933
Try this,
$numbers= Number::whereHas('<Your Eloquent Model>',function($query)use($validated){
$query->where('name', 'like', "%" . $validated['text'] . "%")]);
}
->get();
Upvotes: 0
Reputation: 42762
Assuming you have typical hasMany
/belongsTo
relationships set up between User
and Number
models, this should work:
User::where("name", "like", $test)
->whereHas("numbers", function($q) {
$q->where("name", "like", "%$validated[text]%");
})
->with("numbers", function($q) {
$q->where("name", "like", "%$validated[text]%");
})
->get();
The where()
method, of course, matches users with the desired name. The whereHas()
method further restricts based on the relationship, looking only for users having numbers with a matching name. Assuming you want to retrieve those matching numbers, you have to do the same filter again on the eager load.
Upvotes: 1