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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17766816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:09:58  来源:igfitidea点击:

Eloquent ORM / Laravel - use custom pivot table structure

many-to-manylaravelpivoteloquent

提问by Томица Кора?

I'm trying to build a Laravel app using a customized database structure. I have tables types, units, content, and a pivot table called relations. The structure of the relationstable is such:

我正在尝试使用自定义数据库结构构建 Laravel 应用程序。我有表typesunitscontent和一个名为 的数据透视表relationsrelations表的结构是这样的:

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

In other words, the first three tables have many-to-many relations among themselves, and the fourth one is the pivot table for all the relations. How can I use the Eloquent's BelongsToManymethod with this pivot table structure, i.e. how can I select only the pivot table's records relevant to the given relation? For example, how would I use only the type_unit relations in this:

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

class Type extends Eloquent {

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

}

but at the same time ignore the unit_content relations?

但同时忽略了 unit_content 关系?

回答by Umut Sirin

belongsToManywould accept 3rd and 4th arguments. You can see it in documentation: http://laravel.com/docs/eloquent#relationships

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

But the thing that is not in documentation is that you can constraint your relation by chaining the query builder functions like where, orderByetc.

但是,这不是在文档中的事情是,你可以通过链接查询约束你们的关系建设者功能,如whereorderBy等。

So your code would be something like:

所以你的代码会是这样的:

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

}