2015-04-05 30 views
6

假設我有以下兩種模式之間的Laravel雄辯的關係:更新在Laravel雄辯的一到多的關係

<?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(); 
      } 
     } 
    } 

我要檢索單個用戶和他的設置,我可以做以下內容:

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

現在,這個用戶,我可以更新或使用settingSet方法插入一個設置,如上列出。

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

但是,如果我現在檢索設置,我會得到陳舊的數據。

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

什麼給力的數據,這種關係的INSERT/UPDATE後進行更新/刪除User::settingSet方法或其他類似方法,最好的做法?

+0

你確定你是在救你$用戶> settingSet($鍵,$值)中設定的設置? – martindilling 2015-04-07 09:31:37

+0

@martindilling是的,下一頁刷新顯示新值。 – gpmcadam 2015-04-10 16:20:04

+0

你可以顯示'settingSet'方法嗎? – Gal 2015-04-10 16:48:53

回答

1

您可以使用Lazy Eager Loadingload()函數強制更新數據。

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

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

+0

Eager loading是絕對正確的答案,謝謝!我修改了'User'模型以運行'$ this-> load('settings')'以引入更改,它按預期工作。謝謝。 – gpmcadam 2015-04-10 22:45:12

0

你有這個問題,由於使用查詢生成器,而不是雄辯,我不明白爲什麼你使用兩個,如果你使用雄辯然後使用雄辯如果您使用查詢生成器使用查詢生成器,但不使用,至少在你不可能的時候不行。

我找到setConfigItem方法沒用,因爲你的arent推動用戶進入設置,但設置成用戶所以基本上所有implementions應該對用戶類,而不是在設置類

清除了這一點後,你可以嘗試做這樣的事情 -

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

,你也可以通過改進而不是隻接受1設置在同一時間,你可以接受的設置

順便說一句陣列的這種方法是有一個原因你沒有使用數據透視表?是唯一的foreach用戶的設置?

+0

回答你的問題:1.我在這裏展示了一個人爲的例子,但實際的設置模型不僅僅是用戶設置的責任。 2.不需要數據透視表,請參閱答案1 - 將「設置」視爲可用於多種用例的鍵值存儲區。 – gpmcadam 2015-04-10 22:41:12