Reputation: 1820
i am struck with the following error in the laravel: there are 2 tables users and tracks with many to many relationship and the intermediate table name is track_user i am trying to delete the record but unable to do it
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 Error:
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`))
User Model :
<?php
class User extends Eloquent{
public static $table = 'users';
public function tracks()
{
return $this->has_many_and_belongs_to('Track');
}
Track Model :
<?php
class Track extends Eloquent{
public static $table = 'tracks';
public function users()
{
return $this->has_many_and_belongs_to('User');
}
Controller
//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');
}
Upvotes: 0
Views: 4905
Reputation: 44
From the laravel docs "the opposite of attach is detach:"
Look for it in the http://four.laravel.com/docs/eloquent
Example to leave:
$circle->users()->detach($user_id);
$circle->save();
Upvotes: 2
Reputation: 11
You have to first delete the record from the composite user_track table. Only then can you delete the parent record in the track table.
Upvotes: 1