How to sort by a field of the pivot table of a many-to-many relationship in Eloquent ORM

前端 未结 5 852
甜味超标
甜味超标 2020-12-14 15:22

I have been using Eloquent ORM for some time now and I know it quite well, but I can\'t do the following, while it\'s very easy to do in Fluent.

I h

5条回答
  •  天命终不由人
    2020-12-14 16:26

    I just found something in the user guide, apparently you need the with() method.

    From the User-Guide:

    By default only certain fields from the pivot table will be returned (the two id fields, and the timestamps). If your pivot table contains additional columns, you can fetch them too by using the with() method :

    class User extends Eloquent {
      public function roles()
      {
        return $this->has_many_and_belongs_to('Role', 'user_roles')->with('column');
      }
    }
    

    So you can then use something similar to this when defining your relationship:

    $this->has_many_and_belongs_to('User')->with('playcount');
    

    Example

    I just used this to make sure it works...

    class Song extends Eloquent {
        function users()
        {
            return $this->has_many_and_belongs_to('User')->with('playcount');
        }
    }
    
    class User extends Eloquent {
        function songs()
        {
            return $this->has_many_and_belongs_to('Song')->with('playcount');
        }
    }
    
    // My test method
    class TestOrm extends PHPUnit_Framework_TestCase {
        public function testSomethingIsTrue()
        {
            foreach(User::find(3)->songs()->order_by('playcount')->get() as $song)
                echo $song->name, ': ', $song->pivot->playcount, "\n";
            echo "\n";
            foreach(User::find(3)->songs()->order_by('playcount','desc')->get() as $song)
                echo $song->name, ': ', $song->pivot->playcount, "\n";
        }
    }
    

    Output

    Jingle Bells: 5
    Mary had a little lamb: 10
    Soft Kitty: 20
    The Catalyst: 100
    
    The Catalyst: 100
    Soft Kitty: 20
    Mary had a little lamb: 10
    Jingle Bells: 5
    

    Note: It is no coincidence that without using order_by() the result appears sorted in ascending order by the playcount. I confirmed this through testing (as I do not know yet how to display queries in unit tests), but you should probably not rely on this behaviour.

提交回复
热议问题