问题描述
Laravel版本7.2.5。
我正在使用polymorphic Relationships
存储用于多角色应用程序的access logs (login,logout)
。
数据存储部分工作正常。现在,我需要以分页显示desc
格式的记录列表。但是,它以asc
格式加载数据
SomeModel.PHP
class SomeModel extends Model
{
/**
* polymorphic Relationships
*/
public function loginLog()
{
return $this->morphMany(LoginLog::class,'employable');
}
public function show($token)
{
return self::where([
'token' => $token,])->with([
'loginLog:employable_id,ip,created_at,updated_at'
])->first() ?? null;
}
}
我确实找到了解决方案。但是,以某种方式,它并不适合解决此问题。
这是链接Laravel order results by column on polymorphic table
解决方法
尝试一下
class SomeModel extends Model
{
/**
* Polymorphic Relationships
*/
public function loginLog()
{
return $this
->morphMany(LoginLog::class,'employable')
->latest();
}
}
,
我找到了解决此问题的另一种方法...
class SomeModel extends Model
{
/**
* Polymorphic Relationships
*/
public function loginLog()
{
return $this->morphMany(LoginLog::class,'employable');
}
public function show($token,$pagination = 0)
{
return self::where([
'token' => $token,])->with([
'loginLog' => function ($query) use ($pagination) {
return $query->select([
'employable_id','ip','created_at','updated_at',])
->skip($pagination)
->take(\Common::paginationLimit())
->orderBy('id','DESC');
}
])
->orderBy('id','DESC')
->first('id') ?? null;
}
}
由于我不需要基表的参数,因此,我仅从中获取id
。
此外,通过这种方式,我也可以使用分页(我正在使用loadmore
分页)。