One-to-Many Relationship Update in Laravel Eloquent

Suppose I have a connection between the following two models in Laravel Eloquent:

<?php // user: // - user_id class User extends Model { protected $table = 'users'; public function settings() { return $this->hasMany('Setting'); } public function settingSet($key, $value) { \Setting::setConfigItem($key, $value, $this->user_id); } } // settting: // - setting_key // - setting_value // - user_id class Setting extends Model { public function setConfigItem($key, $value, $user_id) { // Note: I've provided this code here as an example, so it should // exist here only as pseudo-code - it has not been tested and // is outside the scope of this issue but has been requested by // a commenter so I've provided the basis for this method: $existing = \Setting::where(['key' => $key, 'user_id' => $user_id])->first(); if (!$existing) { \Setting::insert([ 'setting_key' => $key, 'setting_value' => $value, 'user_id' => $user_id ]); } else { $existing->setting_value = $value; $existing->save(); } } } 

And I want to get one user and his settings, I can do the following:

 <?php $user = User::with(['setting'])->find(1); 

Now, with this user, I can update or insert the parameter using the settingSet method, as described above.

 <?php $user->settingSet('foo','bar'); 

However, if I extract the settings at this point, I will get outdated data.

 <?php print_r($user->settings); // onoes! 

What is the best practice for forcing data updates for this relationship after INSERT / UPDATE / DELETE in the User::settingSet or other similar methods?

+6
source share
2 answers

You can force update data using the Lazy Eager Loading , load() function.

 print_r($user->load('settings')); 

source: http://laravel.com/docs/5.0/eloquent#eager-loading

+1
source

You have this problem due to using query builder instead of eloquent, I don’t understand why you use both, if you use eloquence, then use eloquent, if you use query builder, use query builder, but do not use both, at least when you have the opportunity not to do this.

I find the setConfigItem method useless, since you arent pushing the user into the setting, but the parameter into the user, so basically all implementations should be in the user class and not in the settings class

After that, you can try to do something like this -

 public function settingSet($key, $value) { $setting = new Setting([ 'setting_key' => $key, 'setting_value' => $value ]); $this->settings()->save($setting); } 

you can also improve this method, instead of taking only 1 setting at a time, when you can accept a set of parameters

By the way, is there a reason why you are not using a pivot table? Are the settings unique to the user?

0
source

Source: https://habr.com/ru/post/984719/


All Articles