【发布时间】:2020-05-05 15:03:13
【问题描述】:
我在school 和associate 模型之间有这些关系:
// School model
public function associates()
{
return $this->belongsToMany('Associate', 'school_associate', 'school_id', 'associate_id')
->withPivot('start_date', 'end_date');
}
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date');
}
我需要在 start_date 之前获得一所学校的所有员工。
这是我尝试但没有成功的方法(在此尝试中,我正在所有学校中搜索):
dd(\App\Associate::with(['schools' => function ($q) {
$q->orderBy('pivot_start_date', 'desc');
}])->toSql());
我得到了这个 sql(注意没有 order by 子句):
select * from `associate`
我尝试像这样编辑关系:
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date')
->orderBy('pivot_start_date', 'desc'); // also tried without "pivot_"
}
根据this post,我也试过了:
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date')
->orderBy('school_associate.start_date', 'desc');
}
但我总是得到相同的查询,结果没有排序。
【问题讨论】:
-
This 解决方案应该适合您。
-
@Remul 我试过没有成功
-
能否将其添加到问题中,以便我查看,可能有错误。
标签: many-to-many sql-order-by laravel-6