2015-09-24 22 views
0

我正在探索Laravel的雄辯作爲我的項目當前的本土活動記錄數據層的替代品。目前,我有一個類User,支持與另一個類的多對多關係,Group。我目前的實現看起來是這樣的:雄辯處理相關實體的緩存嗎?

class User { 

    protected $_groups; // An array of Group objects to which this User belongs 

    public function __construct($properties = []){ 
     ... 
    } 

    public function groups() { 
     if (isset($_groups)) 
      return $_groups; 
     else 
      return $_groups = fetchGroups(); 
    } 

    private function fetchGroups() { 
     // Lazily load the associated groups based on the `group_user` table 
     ... 
    } 

    public function addGroup($group_id) { 
     // Check that the group exists and that this User isn't already a member of the group. If so, insert $group_id to $_groups. 
     ... 
    } 

    public function removeGroup($group_id) { 
     // Check that the User is already a member of the group. If so, remove $group_id from $_groups. 
     ... 
    } 

    public function fresh() { 
     // Reload user and group membership from the database into this object. 
     ... 
    } 

    public function store() { 
     // Insert/update the user record in the `user` table, and insert/update/delete records in `group_user` based on the contents of `$_group_user`. 
     ... 
    } 

    public function delete() { 
     // If it exists, delete the user record from the `user` table, and delete all associated records in `group_user`. 
     ... 
    } 
} 

正如你所看到的,我的課:

  1. 執行與集團的延遲加載,他們查詢後的第一次高速緩存;
  2. 保持User與其Group的關係的內部表示,僅當調用store時纔在數據庫中更新;
  3. 在建立關係時執行健全性檢查,確保Group存在並且在創建新關聯之前尚未與User相關聯。

哪個,如果有這些東西,會雄辯自動照顧我嗎?或者,我的設計在某種程度上有缺陷,是雄辯所能解決的?

你可以假設我將重新實現UserUser extends Illuminate\Database\Eloquent\Model,用洋洋灑灑的belongsToMany爲我目前fetchGroups方法的替代品。

回答

3

雄辯地緩存了內部關係的結果,是的。您可以在Model::getRelationValue()方法中看到該操作。

Eloquent還爲您提供方法來幫助您manage the many-to-many relationship。你可以在現有的API中實現這個功能。但是,這裏有一些事情看出來:

  1. 當使用attach()detach()等等,查詢被立即執行。調用父方法User::save()只會保存用戶的詳細信息,而不是多對多的關係信息。您可以通過暫時存儲傳遞給您的API的ID來解決此問題,然後在撥打User::store()時採取行動。

  2. 使用attach/detach /等時不執行健全性檢查。如果需要的話,將這些應用於您的API中將會很好。

  3. 向/從多對多關係中添加或刪除ID不會影響初始關係查詢的緩存結果。您必須添加邏輯才能將相關模型插入或刪除到集合中。

    例如,假設User有兩個Group s。當我加載用戶時,我可以使用$user->groups訪問這些組。我現在在用戶模型中有一組緩存。如果我再次呼叫$user->groups,它將返回此緩存的Collection。

    如果我使用$user->detach($groupId)刪除一個組,將執行查詢來更新連接表,但緩存的Collection不會更改。同樣適用於添加組。

+0

非常有趣!因此,在某些方面,Eloquent與我的模型做了相反的事情 - 雄辯的行爲立即在數據庫上,但不更新對象的狀態,直到我調用「fresh」爲止,而我的模型立即作用於對象,但沒有更新數據庫,直到我調用'store'。 – alexw

+0

非常漂亮!不過,如果你願意的話,你可以選擇立即在對象上工作,並在'store()'上更新數據庫。只需要編寫更多的代碼,而不是利用開箱即用的功能。既然你已經選擇了一個API,你可以用任何有意義的方式抽象出這個功能。 –

+0

謝謝。我會繼續前進,現在用Eloquent重新實現我目前的設計。如果在以後的道路上我意識到Eloquent的本地方法更好,那麼就這樣吧;-) – alexw