如何在Laravel的雄辩的ORM中通过数据透视表数据进行排序 [英] How to order by pivot table data in Laravel's Eloquent ORM

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

问题描述

在我的数据库中,我有:

In my Database, I have:

  • tops
  • posts
  • tops_has_posts表.
  • tops Table
  • posts Table
  • tops_has_posts Table.

当我在tops表上检索顶部时,我还检索与顶部相关的posts. 但是,如果我想按一定顺序检索这些帖子怎么办? 因此,我在数据透视表tops_has_posts中添加了range字段,我尝试使用Eloquent对结果进行排序,但是它不起作用.

When I retrieve a top on my tops table I also retrieve the posts in relation with the top. But what if I want to retrieve these posts in a certain order ? So I add a range field in my pivot table tops_has_posts and I my trying to order by the result using Eloquent but it doesn't work.

我尝试这个:

$top->articles()->whereHas('articles', function($q) {
    $q->orderBy('range', 'ASC');
})->get()->toArray();

这:

$top->articles()->orderBy('range', 'ASC')->get()->toArray();

都是绝望的尝试.

谢谢.

推荐答案

有两种方法-一种是指定table.field,另一种是使用雄辩的别名pivot_field(如果使用withPivot('field'):

There are 2 ways - one with specifying the table.field, other using Eloquent alias pivot_field if you use withPivot('field'):

// if you use withPivot
public function articles()
{
  return $this->belongsToMany('Article', 'tops_has_posts')->withPivot('range');
}

// then: (with not whereHas)
$top = Top::with(['articles' => function ($q) {
  $q->orderBy('pivot_range', 'asc');
}])->first(); // or get() or whatever

这将起作用,因为雄辩的说法是将withPivot中提供的所有字段都别名为pivot_field_name.

This will work, because Eloquent aliases all fields provided in withPivot as pivot_field_name.

现在,通用解决方案:

$top = Top::with(['articles' => function ($q) {
  $q->orderBy('tops_has_posts.range', 'asc');
}])->first(); // or get() or whatever

// or:
$top = Top::first();
$articles = $top->articles()->orderBy('tops_has_posts.range', 'asc')->get();

这将对相关查询进行排序.

This will order the related query.

注意:以这种方式命名事物不会使您的生活变得艰难. posts不一定是articles,除非确实需要,否则我会使用一个或另一个名称.

Note: Don't make your life hard with naming things this way. posts are not necessarily articles, I would use either one or the other name, unless there is really need for this.

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

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