简体   繁体   English

laravel includesToMany自引用附加关系

[英]laravel belongsToMany self referencing attaching Relation

It is a little bit complicated and confusing... but I have a Model called building and this has a relation to the same model, but with a belongsToMany relation... 这有点复杂和混乱...但是我有一个名为building的模型,它与同一个模型有关系,但是有一个belongsToMany关系...

In this model I have following relation: 在此模型中,我具有以下关系:

# Building Require one or more another Building(s)
    public function requires() {
        return $this->belongsToMany('Building', 'building_require')->withPivot(array(
            'level',
            'updated_at',
            'created_at'
        ));
    }

And now I want fill my intermediate table building_require: 现在我要填充我的中间表building_require:

$obj = Building::find(1);
$obj->requires()->attach(4, array(
        'level' => 1,
        'created_at' => new DateTime,
        'updated_at' => new DateTime,
));

The problem: In my table I find now this row: 问题:在我的表中现在找到以下行:

+-----+--------------+-------------+--------+----------------------+---------------------+
| id  | building_id  | require_id  | level  |     created_at       |     updated_at      |
+-----+--------------+-------------+--------+----------------------+---------------------+
|  1  |           4  |          0  |     1  | 2015-01-29 13:33:45  | 2015-01-29 13:33:45 |
+-----+--------------+-------------+--------+----------------------+---------------------+

But this is wrong.. I expect this: 但这是错误的..我期望这样:

+-----+--------------+-------------+--------+----------------------+---------------------+
| id  | building_id  | require_id  | level  |     created_at       |     updated_at      |
+-----+--------------+-------------+--------+----------------------+---------------------+
|  1  |           1  |          4  |     1  | 2015-01-29 13:33:45  | 2015-01-29 13:33:45 |
+-----+--------------+-------------+--------+----------------------+---------------------+

Why is this happening? 为什么会这样呢?

I can answer myself.. the relation has to be: 我可以回答自己..关系必须是:

# Building Require one or more another Building(s)
    public function requires() {
        return $this->belongsToMany('Building', 'building_require', 'building_id', 'require_id')->withPivot(array(
            'level',
            'updated_at',
            'created_at'
        ));
    }

perhaps somebody will help it. 也许有人会帮上忙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM