简体   繁体   English

Laravel雄辩的关系orderby问题

[英]Laravel Eloquent relationship orderby issue

I have a Objective model which has many Action and every Action has one ActionYear. 我有一个包含许多Action的Objective模型,每个Action都有一个ActionYear。 already defined in model. 已在模型中定义。

How to use orderby to sort action in objective through action_year's specific column. 如何使用orderby通过action_year的特定列对目标中的操作进行排序。

$query = Objective::with('actions.actionYear')
            ->orderBy('action_year.created_at')
            ->get();

this through error Undefined table: 7 ERROR: missing FROM-clause entry for table "action_year" . 这是由于错误而导致的: Undefined table: 7 ERROR: missing FROM-clause entry for table "action_year" How to solve this. 如何解决这个问题。 Thank you. 谢谢。

You can order the eager loaded models with a closure: 您可以订购带有闭合的热切模型:

$query = Objective::with(['actions.actionYear' => function($q){
    $q->orderBy('action_year.created_at');
})->get();

If you use function with() then this only makes sure the named relationship is loaded also to avoid extra need for SQL queries later. 如果使用with()函数,则这只能确保已加载命名关系,以避免以后再需要SQL查询。 Othewise it does not introduce any additional changes compared to Objective::all() 否则,与Objective::all()相比,它不会带来任何其他更改

One way how to achieve sorted collection is to use sortBy() function after loading the data like this 一种实现排序收集的方法是在加载数据后使用sortBy()函数

$query = $query->sortBy(function($objective){
    return $objective->actionYear->created_at;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM