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);
What is the best practice for forcing data updates for this relationship after INSERT / UPDATE / DELETE in the User::settingSet or other similar methods?
source share