dimanche 27 septembre 2015

Eloquent insert multiple records into related model

I'm dealing with four different tables. users, activity, feeds and friends.

friends is the table where two foreign keys exist from users table (user_id and friend_id).

activity is the table where certain activities are hold.

feeds is the table that has two foreign keys, subscriber_id (the user's friend's id) and activity_id. When a user posts something, I want to insert records into feeds table to his friends will see his status updates. I hope it's clear so far. So there will be 20 inserts if there are 20 friends of a user.

Of course, I could do something like below, but that's not the "Laravel way".

    $friends = Auth::user()->friends;
    foreach ($friends as $friend) {
        $feed = new Feed;
        $feed->subscriber_id = $friend->id;
        $feed->activity_id = $status->id;
        $feed->save();
    }

friends relation in the User model.

public function friends() {
    return $this->belongsToMany('App\Models\User', 'friends', 'user_id', 'friend_id');
}

Insert in the controller

$status = new Activity;
$status->user_id = Auth::user()->id;
$status->status = Request::input("text");
$status->activity_type_id = 1;
$result = $status->save(); // OK, status is saved now.

if($result) {
  // insert data into feeds table
   $feed = new Feed;
   $feed->subscriber_id = Auth::user()->friends;
   $feed->activity_id = $status->id;
   $feed->save();
}

It gives exception.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`testdatabase`.`feeds`, CONSTRAINT `feeds_ibfk_1` FOREIGN KEY (`subscriber_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `feeds` (`subscriber_id`, `activity_id`, `updated_at`, `created_at`)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire