Reputation: 1380
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`)
Upvotes: 0
Views: 895
Reputation: 773
$feed->subscriber_id = Auth::user()->friends
is failing because friends is a collection and you're trying to assign it to an single value.
I'm not sure architecturally why you would want the feeds table. You can get the list of activity from someone's friends by just doing a query on activities with some joins.
That being said, as far as I know the only way to update that feeds table is to loop through all of the friends like you're doing in the first example. I'm not sure what makes that not the "Laravel way".
Upvotes: 2