我对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');
}
答案 0 :(得分:2)
从laravel docs&#34;附加的反面是分离:&#34;
在http://four.laravel.com/docs/eloquent
中查找离开的例子:
$circle->users()->detach($user_id);
$circle->save();
答案 1 :(得分:1)
您必须先从复合user_track表中删除该记录。只有这样才能删除轨道表中的父记录。