如何在laravel中对透视表使用latestOfMany?

wecizke3  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(110)

我有两个模型:UserRole。它们具有多对多关系,其中RoleUser充当透视表。
这是我的RoleUser模型:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 
class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class)->using(RoleUser::class);
    }
}

我如何获取使用latestOfMany的最新用户?比如,

return $this->hasOne(User::class)->using(RoleUser::class)->latestOfMany();
t3psigkw

t3psigkw1#

你可以试试这样的

public function latestUser(): HasOne
{
    return $this->hasOne(User::class)->using(RoleUser::class)
        ->latestOfMany('created_at');
}

以及在控制器中

$latestUser = $role->latestUser;

相关问题