【问题标题】:Eloquent ORM / Laravel - use custom pivot table structureEloquent ORM / Laravel - 使用自定义数据透视表结构
【发布时间】:2013-07-19 23:06:09
【问题描述】:

我正在尝试使用自定义数据库结构构建 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关系?

【问题讨论】:

    标签: many-to-many laravel pivot eloquent


    【解决方案1】:

    belongsToMany 将接受第三个和第四个参数。您可以在文档中看到它: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');
        }
    
    }
    

    【讨论】:

    • 很高兴我能帮上忙。 :)
    猜你喜欢
    • 2014-01-11
    • 1970-01-01
    • 2015-02-04
    • 2014-12-20
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2015-06-24
    相关资源
    最近更新 更多