dimanche 27 novembre 2016

laravel eloquent sort by relationship

i have 3 models - User - Channel - Reply

model relations

  • user have belongsToMany('App\Channel');
  • channel have hasMany('App\Reply', 'channel_id', 'id')->oldest();

let's say i have 2 channels - channel-1 - channel-2

channel-2 has latest replies than channel-1

now, i want to order the user's channel by its channel's current reply. just like some chat application. how can i order the user's channel just like this?

  • channel-2
  • channel-1

i already tried some codes. but nothing happen

// User Model
public function channels()
    {
        return $this->belongsToMany('App\Channel', 'channel_user')
                    ->withPivot('is_approved')
                    ->with(['replies'])
                    ->orderBy('replies.created_at'); // error

    }
// also
public function channels()
    {
        return $this->belongsToMany('App\Channel', 'channel_user')
                    ->withPivot('is_approved')
                    ->with(['replies' => function($qry) {
                        $qry->latest();
                    }]);
    }
// but i did not get the expected result



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2fDbKV6
via IFTTT

Aucun commentaire:

Enregistrer un commentaire