Hi,
I have, say, a Post
object that belongsTo
a User
object. The User
object hasMany
Post
objects.
If I want to attach a Post
object to a User
, I can do $user->posts()->save($post)
.
What if I want to detach that relationship? What would the "inverse" of save
be?
Thanks in advance.
l3hash said:
Hi,
try
$user->posts()->detach( $post)
I don't think this will work because its not a many-to-many relationship.
Have you tried just setting the foreign id to null manually?
$user->post_id = null;
$user->save();
I think it is destroy
$user->posts->destroy()
There is also soft deleting, you add a column called deleted_at then it marks records as deleted but keeps them for historical reasons
l3hash said:
Have you tried just setting the foreign id to null manually?
$user->post_id = null; $user->save();
I have. My concern is the following.
$user->posts->save($post);
$user->posts->count(); // returns 1
$post->user_id = null;
$post->save();
$user->posts->count(); // still returns 1, instead of 0!
Any idea? I'm thinking the lack of actual method for doing so leads to model events not being triggering, etc. Yet I don't want to dive into Laravel's internal.
As a fall back I might do what IanSirkit suggested, using destroy()
and then dealing with the removed element as a batch using the withTrashed()
method. But it's not exactly what I wanted to do in the first place...
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community