【问题标题】:many-to-many relationship: order by on pivot table not working多对多关系:按数据透视表排序不起作用
【发布时间】:2020-05-05 15:03:13
【问题描述】:

我在schoolassociate 模型之间有这些关系:

// 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


【解决方案1】:

我以这种方式使用查询生成器解决了。
这个函数在Associate模型中:

public function scopeLast($query, $school_ids = [])
{
    $query->join('school_associate', "{$this->table}.{$this->primaryKey}", '=', 'school_associate.associate_id')
        ->join('school', 'school.school_id', '=', 'school_associate.school_id')
        ->whereIn('school.school_id', $school_ids)
        ->orderBy('school_associate.start_date', 'desc');

    return $query;
}

【讨论】:

    猜你喜欢
    • 2013-04-29
    • 2023-02-05
    • 2016-02-02
    • 1970-01-01
    • 2018-09-23
    • 2014-12-07
    • 2021-05-31
    • 2012-12-27
    • 1970-01-01
    相关资源
    最近更新 更多