1

I have a Laravel project which has User and Order models. User model has relation with sorting to Order model like this:

public function last_order() {
   return $this->hasOne('Order', 'user_id')->orderBy('created_at', 'desc')->limit(1);
}

This returns last order for specific user. It works fine.

I need to also return sorted array of users from the newest order. I tried to do it with Eloquent on repository layer like this:

User::has('last_order')->with('last_order')->orderBy('last_order.created_at', 'desc')->get();

It doesn't work. I also tried it with sortBy method, same result. It returns me, that last_order table is not exist.

Could you advice me, how to easily sorted some like this with Eloquent (not in service layer, and without raw select)?

Thank you.

1
  • what is name of order table ? Commented Jun 27, 2019 at 19:04

2 Answers 2

1

sortBy() using dot notation works fine after you get() the collection.

User::has('last_order')->with('last_order')->get()->sortByDesc('last_order.created_at');

I also noticed the last_order() relation is already sorted. This will not work unless you create a different relationship that doesn't limit the return to 1 and isn't pre-sorted.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you've a right . It's not work with already sorted relation. Now I found solution for this (little different access like I tried before), and I'll add it to answer. Anyway, thank you for your answer (+1)
0

It occurs to me:

public function scopeLasorder($query)
{
    return $query->join(
        with(new Orden())->getTable(), 'user_id', '=', 'id' //id de User
    )->whereNotNull('last_order');
}

And to execute

User->lastorder->orderBy(new Orden())->getTable().'.created_at', 'desc')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.