S
S
Sergey Melnikov2022-01-11 14:26:59
Laravel
Sergey Melnikov, 2022-01-11 14:26:59

How to implement a mapping of the settings table to a specific record?

How to implement mapping in a model with a settings table in a Laravel project?
Example - there is a User
Id, Name
table and a Settings
Id, Param, Value, UserId table
Direct where to dig. To get the associated settings for that user from the User model.

I think that you need to have a Settings model like this:

class Settings {
 
   protected $param1
   protected $param2
 
}
 
class User {
 
   protected $name
   protected $settings
 
}

And how to work to work from the User model with various parameters associated only with this user?
Maybe this is a pattern, and does it have a name?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2022-01-11
@delphinpro

The model should be called Setting
Table settings
Make a second table setting_user
user_id | setting_id
I pay attention to the naming of fields and tables and other entities adopted in Laravel. By following these conventions, you will make it easier for yourself to create links.
Next, smoke the dock for a many-to-many connection
Create a relationship for the user

public function settings() {
  return $this->belongsToMany(Setting::class);
}

Now you can get all his settings from the user.
$user->settings
Create a new one
$user->settings->create([...])
, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question