How to order by pivot table data in Laravel's Eloquent ORM

前端 未结 5 691
难免孤独
难免孤独 2020-12-17 11:11

In my Database, I have:

  • tops Table
  • posts Table
  • tops_has_posts Table.

When I retrieve a

5条回答
  •  臣服心动
    2020-12-17 11:15

    In Laravel 5.4 I have the following relation that works fine in Set model which belongsToMany of Job model:

    public function jobs()
        {
            return $this->belongsToMany(Job::class, 'eqtype_jobs')
                   ->withPivot(['created_at','updated_at','id'])
                   ->orderBy('pivot_created_at','desc');
        }
    

    The above relation returns all jobs that the specified set has been joined ordered by the pivot table's (eqtype_jobs) field created_at DESC.

    The SQL printout of $set->jobs()->paginate(20) Looks like the following:

    select `jobs`.*, `eqtype_jobs`.`set_id` as `pivot_set_id`,
    `eqtype_jobs`.`job_id` as `pivot_job_id`,
     `eqtype_jobs`.`created_at` as `pivot_created_at`,
    `eqtype_jobs`.`updated_at` as `pivot_updated_at`,
     `eqtype_jobs`.`id` as `pivot_id` from
    `jobs` inner join `eqtype_jobs` on `jobs`.`id` = `eqtype_jobs`.`job_id` where
    `eqtype_jobs`.`set_id` = 56
     order by `pivot_created_at` desc limit 20 offset 0
    

提交回复
热议问题