我一直在使用laravel一段时间,我只是好奇哪个性能更好。在这种情况下,我有两个表部门表和一个单位表,其结构如下
部门表
Field Type Null Key
---------- ---------------- ------- ------
id int(10) unsigned NO PRIMARY
name varchar(255) NO
UNIT TABLE
Field Type Null Key
------------- ---------------- ------ ------
id int(10) unsigned (NULL) PRIMARY
unit varchar(255) (NULL)
department_id int(10) unsigned (NULL) FOREIGN
created_at timestamp (NULL)
updated_at timestamp (NULL)
在Department
模型中,我有Unit
hasMany
和unit
模型,我的部门有belongsTo
现在我的问题是,如果我想让部门中的所有单位在接近一个和接近两个
之间采用最佳方法APPROACH ONE
$department = Department::find($id);
$units = $department->unit;
APPROACH TWO
$units = DB::table('units AS a')
->select(array('a.id AS id','department_id', 'unit'))
->join('departments AS b', 'a.department_id', '=', 'b.id')
->where('b.id', '=', $id)
->get();
哪种方法更快更好。
感谢。
答案 0 :(得分:1)
APPROACH ONE 。
如果真的存在差异更快,我们将谈论微优化,对于这些情况,我们将采用更清晰,最易理解的方式,所以第一个。
我还想推荐其他改进措施:
一个部门有很多单位,因此关系名称应为units
,而不是unit
。
$units = $department->units;
尽可能使用隐式绑定。
public function yourMethod (Department $department)
{
$units = $department->units;
return view('your-view', compact('units'));
}
<强>更新强>
我使用Laravel Debugbar在我的项目中复制了一个示例,这些是每个查询执行5次的结果:
APPROACH ONE :
〜314μs
APPROACH TWO :
〜322μs
正如您所看到的,没有区别,或者至少它是无关紧要的。因此,具有相同的性能,您应该采用第一种方法,因为它是更好的质量代码。