3分钟短文 | Laravel 根据关联模型条目数量排序,怎么做?
2 年前
· 来自专栏
程序员小助手
引言
在laravel中我们使用模型操作数据库表,同时使用 hasOne belongTo hasMany 等关联关系模型 建立不同模型之间的关联。对于简单的查询操作这完全应付的来。
可是现实的业务需求往往充满变数,今天我们就说一个需求, 根据关联模型的数量进行排序,应该如何写代码。
学习时间
我们用实例进行解释,首先是表结构,为了简化操作,只罗列出主要的字段。首先是 hackathons 表的两个字段:
- id
- name
- begins
- ends
- description
然后是 user 表的字段:
- id
- name
还有一个关联表 hackathon_user 字段:
- hackathons_id
- user_id
好了,基础数据已经建立,接着我们使用laravel的模型操作数据库表。首先声明 Hackathons 模型:
class Hackathon extends Model
protected $fillable = ['name', 'begins', 'ends', 'description'];
protected $table = 'hackathons';
public function owner()
return $this->belongsToMany('User', 'hackathon_owner');
public function participants()
return $this->belongsToMany('User');
public function type()
return $this->belongsToMany('Type');
}
其中有一个 Type 模型因为与本文所讨论问题无关,因此不予列出。接着定义关联表的模型:
class HackathonParticipant extends Model
protected $fillable = ['hackathon_id', 'user_id'];
protected $table = 'hackathon_user';
public function user()
return $this->belongsTo('User', 'user_id');
public function hackathon()
return $this->belongsTo('Hackathon', 'hackathon_id');
}
这就是我们需要的基础类,接着说如何排序。如果不考虑性能问题,或者筛选出的数据量还不足以让我们考虑到性能问题, 那么可以先把结果数据集整个返回,然后使用 laravel collection 集合进行排序和操作。 代码写起来像下面这样:
$hackathons = Hackathon::with('participants')->get()->sortBy(function($hackathon)