Laravel: how to sort a collection with hasMany field

197 views Asked by At

I have five tables:

details having fields id, name and has hasMany relation with contributions.

purpose having fields id, name and has hasMany relation with contributions.

period having fields id, name and has hasMany relation with contributions.

user having fields id, name and has hasMany relation with contributions.

and

contributions having id, amount and "belongsTo" relation with user_id, detail_id, purpose_id, period_id

Now, I want to get all contributions of a specific user (filtered by user_id) and then sort the result by period.name, detail.name and purpose.name.

Any suggestions?

The question has been identified as possible duplicate of Laravel orderBy on a relationship . However there is a basic difference.

there, there is relation between user and comment & user and post. however in my case, there isn't any relation between user and details/purposes/periods tables.

<?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

is possible in that case, but by same analogy, in my case, class User doesn't have any details() function to get hasMany relations. My user has relation with only contributions table and contributions table has relations with details purpose etc tables.

hope I am able to clarify the difference.

0

There are 0 answers