无法删除一对多关系中的记录 laravel eloquent
Posted
技术标签:
【中文标题】无法删除一对多关系中的记录 laravel eloquent【英文标题】:unable to delete record in one to many relationship laravel eloquent 【发布时间】:2013-01-05 09:07:20 【问题描述】:我对 laravel 中的以下错误感到震惊: 有 2 个表用户和轨道具有多对多关系,中间表名称是 track_user 我正在尝试删除记录但无法删除
Unhandled Exception
Message:
Call to a member function track() on a non-object
Location:
C:\wamp\www\integron\application\controllers\track.php on line 50
Mysql 错误:
SQL query:
DELETE FROM `integron`.`tracks` WHERE `tracks`.`id` =2
mysql said:
#1451 - Cannot delete or update a parent row: a foreign key constraint fails (`integron`.`track_user`, CONSTRAINT `track_user_project_id_foreign` FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`))
用户模型:
<?php
class User extends Eloquent
public static $table = 'users';
public function tracks()
return $this->has_many_and_belongs_to('Track');
跟踪模型:
<?php
class Track extends Eloquent
public static $table = 'tracks';
public function users()
return $this->has_many_and_belongs_to('User');
控制器
//this funciton is working properly
public function post_trackUpdate($id)
$track = Track::find($id);
$track->name = Input::get('name');
$track->description = Input::get('desc');
$track->save();
//this funciton is not working properly
public function get_trackDelete($id)
$track = Track::find($id);
$track->delete();
..
//an alternate which i tried but didnt work either
public function get_trackDelete($id)
$user=User::find($id);
$user->tracks()->delete();
Session::flash('result','track Details deleted');
return Redirect::to('track');
【问题讨论】:
【参考方案1】:来自 laravel 文档“附加的反面是分离:”
在http://four.laravel.com/docs/eloquent中寻找它
离开的例子:
$circle->users()->detach($user_id);
$circle->save();
【讨论】:
【参考方案2】:您必须首先从复合 user_track 表中删除记录。只有这样,您才能删除跟踪表中的父记录。
【讨论】:
如何删除复合表中的记录?以上是关于无法删除一对多关系中的记录 laravel eloquent的主要内容,如果未能解决你的问题,请参考以下文章