gpt4 book ai didi

php - 如何在 Laravel 的 Eloquent ORM 中按数据透视表数据排序

转载 作者:可可西里 更新时间:2023-11-01 06:31:25 25 4
gpt4 key购买 nike

在我的数据库中,我有:

  • top 表格
  • posts
  • tops_has_posts 表。

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

我试试这个:

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

还有这个:

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

两者都是孤注一掷的尝试。

提前谢谢你。

最佳答案

有两种方法 - 一种是指定 table.field,另一种是使用 Eloquent 别名 pivot_field 如果你使用 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

现在,通用解决方案:

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

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

注意:不要用这种命名方式让您的生活变得艰难。 posts 不一定是 articles,我会使用一个或另一个名称,除非真的需要这个。

关于php - 如何在 Laravel 的 Eloquent ORM 中按数据透视表数据排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26551078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com