如何在雄辩ORM中通过多对多关系的枢轴表的字段进行排序 [英] How to sort by a field of the pivot table of a many-to-many relationship in Eloquent ORM

查看:120
本文介绍了如何在雄辩ORM中通过多对多关系的枢轴表的字段进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用雄辩的ORM一段时间,我知道的很好,但我不能做以下,而这是非常容易的流利



我有一个多对多的歌曲的用户,中间表是song_user(就像它应该是)。根据播放次数,我想获得用户的热门歌曲。当然,播放次数存储在中间表中。



我可以在流利中执行:

  $ songs = DB :: table('songs')
- > join('song_user','songs.id','=','song_user.song_id' b $ b - > where('song_user.user_id','=',$ user-> id)
- > orderBy(song_user.play_count,desc)
- > ;得到();

简单。但是我想在口才中做到这一点,当然不起作用:

  $ songs = Song :: 
with(array(song_user=> function($ query)use($ user){
$ query-> where(user_id,=,$ user - > id) - > orderBy(play_count,desc);
}))


解决方案

不知道如果你打算移动到Laravel 4,但是这是一个有说服力的例子,通过数据透视表字段排序:

  public function songs(){
return $ this
- > belongsToMany('Song')
- > withPivot('play_count ')
- > orderBy('pivot_play_count','desc');
}

withPivot 雄辩的,并将$ code> play_count 字段从数据透视表添加到其已包含的其他键。所有的数据透视表字段都在结果中以 pivot 为前缀,因此您可以直接在 orderBy 中引用它们。 / p>

我不知道在Laravel 3中会是什么样子,但也许这将有助于指导您正确的方向。



干杯!


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 have users with a many-to-many songs, intermediate table being song_user (like it should be). I'd like to get the top songs of a user, judging by the play count. Of course, play count is stored in the intermediate table.

I can do it in Fluent:

$songs = DB::table('songs')
    ->join('song_user', 'songs.id', '=', 'song_user.song_id')
    ->where('song_user.user_id', '=', $user->id)
    ->orderBy("song_user.play_count", "desc")
    ->get();

Easy. But I want to do it in Eloquent, which of course doesn't work:

$songs = Song::
    with(array("song_user" => function($query) use ($user) {
        $query->where("user_id", "=", $user->id)->orderBy("play_count", "desc");
    }))

解决方案

Not sure if you plan to move to Laravel 4, but here's an Eloquent example for sorting by a pivot tables fields:

public function songs() {
  return $this
    ->belongsToMany('Song')
    ->withPivot('play_count')
    ->orderBy('pivot_play_count', 'desc');
}

withPivot is like the eloquent with and will add the play_count field from the pivot table to the other keys it already includes. All the pivot table fields are prefixed with pivot in the results, so you can reference them directly in the orderBy.

I've no idea what it would look like in Laravel 3, but perhaps this will help point you in the right direction.

Cheers!

这篇关于如何在雄辩ORM中通过多对多关系的枢轴表的字段进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆