Eloquent ORM / Laravel - 使用自定义数据透视表结构

时间:2013-07-20 21:21:21

标签: many-to-many laravel pivot eloquent

我正在尝试使用自定义数据库结构构建Laravel应用程序。我有表typesunitscontent和名为relations的数据透视表。 relations表的结构如下:

---------------------------------------------
| id | relation_type | first_id | second_id |
---------------------------------------------
|  1 |   type_unit   |     1    |    2      |
---------------------------------------------
|  2 | unit_content  |     2    |    3      |
---------------------------------------------

换句话说,前三个表之间有多对多的关系,第四个表是所有关系的数据透视表。如何在此数据透视表结构中使用Eloquent的BelongsToMany方法,即如何仅选择与给定关系相关的数据透视表的记录?例如,我将如何仅使用type_unit关系:

class Type extends Eloquent {

    public function units()
    {
        return $this->belongsToMany('Unit', 'relations');
    }

}

但同时忽略unit_content关系?

1 个答案:

答案 0 :(得分:13)

belongsToMany会接受第3和第4个参数。您可以在文档中看到它:http://laravel.com/docs/eloquent#relationships

但是文档中没有的东西是你可以通过链接whereorderBy等查询构建器函数来约束你的关系。

所以你的代码应该是这样的:

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');
    }

}