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.