简体   繁体   中英

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...

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:

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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