Laravel Model 中附加的字段如何使用排序和分页功能?
class Server extends Model
{
protected $table = 'servers';
protected $primaryKey = 'server_id';
protected $appends = ['online'];
public function getOnlineAttribute()
{
$redis = Redis::connection('db0');
if ($redis->hexists('entrance_online', $this->server_id)) {
return $redis->hget('entrance_online', $this->server_id);
} else {
return 0;
}
}
}
如上面的代码所示,一个模型类对应mysql的一张表,表中已有的字段可以使用mysql的排序功能,laravel已封装好;模型中有一个online字段是附加上去的,表示这台服务器当前在线的人数,因为online数据会经常变动,所以把数据存放在了redis中,那么在使用的时候如何根据online字段进行排序和分页?
我的思路是先把servers表中的数据从mysql全读出来,然后使用PHP的数组函数进行排序,再然后对上一步的数据进行array_chunk分块,根据页码返回对应区块的数据,但感觉这样做不够优雅,数据量大的时候会出现内存不够或者性能问题。
社区的各路精英,有没有更优雅的解决办法呢?
关于 LearnKu
推荐文章: