Eloquent是什么
Eloquent 是一個 ORM,全稱為 Object Relational Mapping,翻譯為 “對象關系映射”(如果只把它當成 Database Abstraction Layer 數組庫抽象層那就太小看它了)。所謂 “對象”,就是本文所說的 “模型(Model)”;對象關系映射,即為模型間關系。中文文檔: http://laravel-china.org/docs/eloquent#relationships
引用
在實際開發中經常用到分庫分表,比如用戶表分成 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 函數的實現方法,沒有地方可以設置表名,只好復制一份 HasOne 方法進行修改。比如改成 myHasOne,加上 $table 參數可以設置表名,并且在對象實例化后調用 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); }
不知道大家有沒有更優雅的方式。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。