Laravel透视表关系

时间:2018-01-26 14:30:13

标签: laravel

我在绕着Laravel的关系缠身时遇到了很大的麻烦。

在我的应用程序中有项目有任务。我最终得到了一个数据透视表(它还有一些额外的列):

CREATE TABLE `tasks_projects` (
`pivot_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id` int(11) DEFAULT NULL,
`project_id` int(11) DEFAULT NULL,
`allocated_hours` int(11) DEFAULT NULL,
`display_order` int(11) DEFAULT NULL,
`hourly_price` int(3) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`pivot_id`)
)

这似乎不合逻辑,因为'id'列引用了Task的id,并且对pivot表的任何直接更新都因此而出错。

在\ App \ Project.php我有:

public function project_tasks() {
    return $this->hasManyThrough('\App\Task', '\App\TasksProjects', "project_id", "id");
}

在\ App \ Task.php我有:

public function projects() {
    return $this->belongsToMany('\App\Project', 'tasks_projects');
}

$ project-> project_tasks()返回正确的任务,我认为我已经完成了 - 但现在我尝试使用$ project-> project_tasks() - > updateExistingPivot来更新数据透视表行,并且我得到的只是

Call to undefined method Illuminate\Database\Query\Builder::updateExistingPivot()

1 个答案:

答案 0 :(得分:1)

通过多对多关系,您应该在数据透视表上设置相关模型的ID:

CREATE TABLE `project_task` (
`project_id` int(11) DEFAULT NULL,
`task_id` int(11) DEFAULT NULL,
`allocated_hours` int(11) DEFAULT NULL,
`display_order` int(11) DEFAULT NULL,
`hourly_price` int(3) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`pivot_id`)
)

雄辩的命名约定规定数据透视表应按字母顺序使用两个相关模型的单数形式命名。

两个模型将定义belongsToMany关系:

public function projects() {
    return $this->belongsToMany('\App\Project');
}

public function tasks() {
    return $this->belongsToMany('\App\Task');
}