Laravel 按数据透视表时间戳排序,多对多关系

问题描述 投票:0回答:1

我目前正在按模型(Url 模型)的时间戳进行排序,但我想按数据透视表的时间戳进行排序。尝试了一些事情,但没有骰子。有人可以帮我看看我哪里出了问题吗?

这就是我目前所拥有的。

class Url extends Model
{
    use HasFactory;
    // ... etc ...
    public function users()
    {
        return $this->belongsToMany(User::class)->withTimestamps();
    }
    public function hostname()
    {
        return $this->belongsTo(Hostname::class);
    }   
}

class User extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable;
    // ... etc ...
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    public function getJWTCustomClaims()
    {
        return [];
    }
    public function urls()
    {
        return $this->belongsToMany(Url::class)
            ->withTimestamps();
    }
}

这是存储库中的一个片段。

public function paginate() 
 { 
 return Url::query()
 ->with(['users'=>function($query)
 {
 $query
 ->select('id', 'username', 'slug')
 ->where([
 'active'=>true
 ]);
 }])
 ->with(['hostname'=>function($query)
 {
 $query
 ->select('id', 'hostname', 'slug')
 ->where([
 'active'=>true
 ]);
 }])
 ->select('id', 'url', 'title', 'hostname_id', 'updated_at')
 ->where([
 'active'=>true
 ])
 ->orderByDesc('created_at') // <-- replace this
 ->paginate();
 }

对此有任何想法,我们将不胜感激。

php laravel eloquent many-to-many sql-order-by
1个回答
0
投票

您需要加入:

public function paginate() 
{ 
    return Url::query()
        ->with(['users' => function($query) {
            $query->select('id', 'username', 'slug')
                  ->where(['active' => true]);
        }])
        ->with(['hostname' => function($query) {
            $query->select('id', 'hostname', 'slug')
                  ->where(['active' => true]);
        }])
        ->join('url_user', 'urls.id', '=', 'url_user.url_id') // join with the pivot table
        ->select('urls.id', 'urls.url', 'urls.title', 'urls.hostname_id', 'urls.updated_at')
        ->where(['urls.active' => true])
        ->orderByDesc('url_user.created_at')
        ->paginate();
}
© www.soinside.com 2019 - 2024. All rights reserved.