Том*_*раћ 5 pivot many-to-many laravel eloquent
我正在尝试使用自定义数据库结构构建Laravel应用程序.我有表types
,units
和content
,以及一个名为的数据透视表relations
.relations
表的结构是这样的:
---------------------------------------------
| id | relation_type | first_id | second_id |
---------------------------------------------
| 1 | type_unit | 1 | 2 |
---------------------------------------------
| 2 | unit_content | 2 | 3 |
---------------------------------------------
Run Code Online (Sandbox Code Playgroud)
换句话说,前三个表之间具有多对多关系,第四个表是所有关系的数据透视表.如何在BelongsToMany
此数据透视表结构中使用Eloquent 方法,即如何仅选择与给定关系相关的数据透视表的记录?例如,我将如何仅使用type_unit关系:
class Type extends Eloquent {
public function units()
{
return $this->belongsToMany('Unit', 'relations');
}
}
Run Code Online (Sandbox Code Playgroud)
但同时忽略unit_content关系?
Umu*_*rin 13
belongsToMany
会接受第三和第四个论点.您可以在文档中看到它:http://laravel.com/docs/eloquent#relationships
但是文档中没有的东西是你可以通过链接查询构建器函数来约束你的关系where
,orderBy
等等.
所以你的代码将是这样的:
class Type extends Eloquent {
public function units()
{
return $this->belongsToMany('Unit', 'relations', 'first_id', 'second_id')
->withPivot(['relation_type'])
->where('relations.relation_type', '=', 'type_unit');
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5693 次 |
最近记录: |