Answer the question
In order to leave comments, you need to log in
How to correctly link two models to a pivot table?
There are models:
Role::create([
"name" => "Пользователь",
"slug" => "user"
]);
RoleSettings::create([
'setting_title' => 'Уведомлять о новых ответах в комментариях',
'setting_slug' => 'comment_reply_enabled',
'role_id' => Role::where('slug','user')->first()->id
]);
$role = Role::where('slug','user')->first();
$user->role()->attach($role);
/**
* Прикрепляем пользователю роль по умолчанию (пользователь)
*/
$user_settings = [];
$role_settings = RoleSettings::where('role_id',1)->get();
foreach ($role_settings as $role_setting) {
$user_settings[$role_setting->id] = ['value' => $role_setting->default_value];
}
$user->settings()->attach($user_settings);
"id": 1,
"name": "Sklyarov Alexey",
"email": "---",
"email_verified_at": null,
"current_team_id": null,
"profile_photo_path": "profile-photos/mU1dOnx7YhDWY5OEAxRKgkijwRghRW7XgI7Rp5IT.jpeg",
"created_at": "2020-09-19T12:22:28.000000Z",
"updated_at": "2020-09-19T12:26:46.000000Z",
"profile_photo_url": "http://localhost/storage/profile-photos/mU1dOnx7YhDWY5OEAxRKgkijwRghRW7XgI7Rp5IT.jpeg",
"settings": [
{
"id": 1,
"role_id": 1,
"setting_title": "Уведомлять о новых ответах в комментариях",
"setting_slug": "comment_reply_enabled",
"default_value": 1,
"pivot": {
"user_id": 1,
"setting_id": 1,
"value": "1"
}
},
{
"id": 2,
"role_id": 1,
"setting_title": "Уведомлять о новых ответах на почту",
"setting_slug": "comment_reply_mail_enabled",
"default_value": 1,
"pivot": {
"user_id": 1,
"setting_id": 2,
"value": "1"
}
}
],
pivot
. Obviously this has to do with how I associate the role settings with the user. In the User model, I do it like this:/**
* Получить настройки пользователя
*/
public function settings()
{
return $this->belongsToMany(RoleSettings::class,'users_settings','user_id','setting_id')->withPivot('value');
}
Answer the question
In order to leave comments, you need to log in
See how it is implemented in ready-made packages, for example here
If I understand correctly, then this decision falls on your needs.
You linked the models correctly.
Additional pivot table data will be in pivot.
There is no problem accessing this data:
// Условимся, что settings не пустой
$user->settings[0]->pivot->value
// Можешь переименовать
$this->belongsToMany(RoleSettings::class,'users_settings','user_id','setting_id')
->withPivot('value')
->as('info');
// После писать так
$user->settings[0]->info->value
В общем, у тебя все ок.
<a href="https://laravel.com/docs/8.x/eloquent-relationships#many-to-many">Many to many</a>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question