Question

Considering this closure:

$users = User::with(array('posts' => function($query) {
    $query->orderBy('created_at', 'desc');
}))->get();

How do I pass $query to get() such as ->get('query')?

If this is even possible.

Update:

This is a follow up to the accepted answer.

Below is the resulting code, for a similar situation, based in $query->getRelation() tip.

$query = Ticket::with(array('user' => function($q) use ($search) {
    $q->where('name', 'LIKE', '%'. $search .'%')->orWhere('username', 'LIKE', '%'. $search .'%');
}));

return $query->whereIn('user_id', $query->getRelation('user')->lists('id'))->paginate(10);

Another one of the many ways to achieve it in Eloquent.

Was it helpful?

Solution

It doesn't make any sense to me but I think you may try this to get the $query instance:

$users = User::with(array('posts' => function($query) {
    $query->orderBy('created_at', 'desc');
}));
$relation = $users->getRelation('posts');

The $relation will contain an instance of Illuminate\Database\Eloquent\Relations\HasMany (hopefully) but not sure how you use it but you may use $relation->getForeignKey() to get the foreignkey property. Finally, $users->get() will execute the query.

You may also get the relation ($query) object using something like this:

$user = User::query();
$relation = $user->getRelation('posts');
dd($relation); // Illuminate\Database\Eloquent\Relations\HasMany

P/S: It's not clear to me what you are going to do so if it helps and you get what you wanted to do then please share the idea/thing in comment. Thanks!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top