Laravel模型間關系設置分表方法詳解

Laravel模型間關系設置分表方法詳解

在實際開發中經常用到分庫分表,比如用戶表分成 100 張,那么這個時候查詢數據需要設置分表,比如 laravel 的 model 類中提供了 settable 方法:

推薦教程:《laravel教程

/** ?*?Set?the?table?associated?with?the?model. ?* ?*?@param??string??$table ?*?@return?$this ?*/ public?function?setTable($table) { ????$this->table?=?$table; ? ????return?$this; }

那么對數據表的增刪改查需要先 new 一個模型實例,再設置表名。如:

(new?Circle())->setTable("t_group_"?.?hashID($userid,?20)) ->newQuery() ->where('group_id',?$request->group_id) ->update($attributes);

這個很簡單,那么在模型間關系比如 HasOne,HasMany 等使用這種方式的情況下,如何設置分表呢?

找了半天沒找到好的辦法,以 HasOne 為例,只好復制 Model 類中的 HasOne 方法,改成 myHasOne,并傳入表名,并且在函數里對象實例化后調用 setTable,果然可以。

代碼如下:

public?function?detail() { ????return?$this->myHasOne(Circle::class,?'group_id',?'group_id',?'t_group_'?.?hashID($this->userid,?20)); } ? public?function?myHasOne($related,?$foreignKey?=?null,?$localKey?=?null,?$table) { ????$foreignKey?=?$foreignKey??:?$this->getForeignKey(); ? ????$instance?=?(new?$related)->setTable($table); ? ????$localKey?=?$localKey??:?$this->getKeyName(); ? ????return?new?HasOne($instance->newQuery(),?$this,?$instance->getTable()?.?'.'?.?$foreignKey,?$localKey); }

不知道大家有沒有更優雅的方式。

? 版權聲明
THE END
喜歡就支持一下吧
點贊13 分享