如何在 Eloquent ORM 中按多对多关系的数据透视表的字段排序 [英] How to sort by a field of the pivot table of a many-to-many relationship in Eloquent ORM

查看:21
本文介绍了如何在 Eloquent ORM 中按多对多关系的数据透视表的字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 Eloquent ORM 有一段时间了,我对它非常了解,但我不能执行以下操作,而 在 Fluent 中很容易做到.

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.

我的用户拥有多对多的歌曲,中间表是 song_user(应该是这样).我想根据播放次数来获取用户的热门歌曲.当然,播放次数存储在中间表中.

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.

我可以在 Fluent 中做到:

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();

简单.但我想在 Eloquent 中做到这一点,这当然行不通:

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");
    }))

推荐答案

不确定您是否打算迁移到 Laravel 4,但这里有一个 Eloquent 示例,用于按数据透视表字段进行排序:

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 就像 eloquent with 并将数据透视表中的 play_count 字段添加到它已经包含的其他键.结果中所有数据透视表字段都以pivot为前缀,因此您可以直接在orderBy中引用它们.

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.

我不知道它在 Laravel 3 中会是什么样子,但也许这会帮助您指明正确的方向.

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

干杯!

这篇关于如何在 Eloquent ORM 中按多对多关系的数据透视表的字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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