laravel belongsToMany自引用附加关系

时间:2015-01-29 12:43:01

标签: php laravel relation

有点复杂和令人困惑...... 但是我有一个名为building的模型,它与同一个模型有关系,但是有一个belongsToMany关系......

在这个模型中,我有以下关系:

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

现在我想填写我的中间表building_require:

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

问题: 在我的表格中,我现在找到这一行:

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

但这是错误的......我希望如此:

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

为什么会这样?

1 个答案:

答案 0 :(得分:0)

我可以自己回答......关系必须是:

# 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'
        ));
    }
也许有人会帮助它。