這篇文章將為大家詳細講解有關Laravel模型間關系設置分表,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
在實際開發中經常用到分庫分表,比如用戶表分成 100 張,那么這個時候查詢數據需要設置分表,比如 Laravel 的 Model 類中提供了 setTable 方法:
/** * 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); }
不知道大家有沒有更優雅的方式。
關于“Laravel模型間關系設置分表”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。