How to order by pivot table data in Laravel#39;s Eloquent ORM(如何在 Laravel 的 Eloquent ORM 中按数据透视表数据排序)
问题描述
在我的数据库中,我有:
In my Database, I have:
tops表格posts表格tops_has_posts表格.
topsTablepostsTabletops_has_postsTable.
当我在 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,另一种使用 Eloquent 别名 pivot_field if你使用 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
这会起作用,因为 Eloquent 将 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 的 Eloquent ORM 中按数据透视表数据排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Laravel 的 Eloquent ORM 中按数据透视表数据排序
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
