V
V
Volodymyr2022-04-20 01:53:13
Laravel
Volodymyr, 2022-04-20 01:53:13

How to synchronize multiple table columns in Laravel relationships?

Hello!

How to synchronize multiple table columns in Laravel relationships?

There is a users table and a User model with declared relationships to the users_params table and the UserParam model:

public function syncParams()
    {
        return $this->belongsToMany(UserParam::class, 'users_params', 'user_id', 'field1');
    }

The users_params table has the following columns: id, user_id, field1,
field2
$user = User::find(2022);
        $test = ;
        $user->syncParams()->sync($test);

When synchronization occurs in an incomprehensible way, the first data ('field1'=>'Test1','field2'=>'Test2') always flies away to nowhere, the last two arrays always remain.

Tell me how you can create, update / synchronize several columns in a table?
The above method works perfectly for one column, but does not work with two.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Volodymyr, 2022-04-20
@volodyalesha86

I solved the problem like this: I
added another field_id column to the users_params table and made it PRIMARY_KEY like the ID column: id, field_id, user_id, field1, field2
In the User model, I wrote the following:

return $this->belongsToMany(UserParam::class, 'users_params', 'user_id', 'field_id');

Now everything is synchronized perfectly, auto-incrementing is going on by ID, fields are counted by FIELD_ID for each user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question