1
votes

I'm struggling with Eloquent relationships in my Laravel project.

I have a 'user' table and a 'user_lines' table in my database. The 'user_lines' table has a' user_id' field that corresponds to the 'id' field in 'users', in a classic master-detail relationship.

The User model has a hasMany relationship to the UserLine model. The UserLine model has a belongsTo relationship to the User model.

In my application I have a user form that contains several userlines. During form submits those userlines can be added, altered or deleted. So far I find myself iterating the submitted userlines and manually creating, updating and deleting the userlines. I feel I'm missing out on the attach/detach/sync methods Eloquent provides but I can't seem to get them to work.

$user->lines()->attach or $user->lines()->sync               

gives me an exception telling me these are undefined methods on Illuminate\Database\Query\Builder.

$user->lines()->createMany($lines) 

works but that just creates new lines, it does not update existing lines and delete removed lines.

2

2 Answers

1
votes

The attach, detach and sync methods are for the many-to-many relationship and not for one-to-many. So, you need to iterate over lines and add or edit them one by one.

1
votes

Your tables relationships isone-to-many and for attaching to such relationships you should use save, saveMany or create methods.

for updating you could do something like this:

$user->lines()->where('field',$something)->update($array);

The attach, detach and sync methods are for the many-to-many relationships and not for one-to-many.