分库分表在实际开发中经常用到。比如user表被分成100张。这时候查询数据需要建立分表。比如Laravel的Model类中提供了setTable方法:/***设置模型关联的表。**@paramstring$table*@return$this*/publicfunctionsetTable($table){$this->table=$table;return$this;}then对数据表进行增删改查,需要先新建一个模型实例,然后设置表名。如:(newCircle())->setTable("t_group_".hashID($userid,20))->newQuery()->where('group_id',$request->group_id)->update($attributes);这个很简单,那么HasOne、HasMany等模型之间的关系使用这种方法时,如何设置分表呢?找了半天也没找到好的解决办法。以HasOne为例,我只好复制Model类中的HasOne方法,改成myHasOne,并传入表名,在函数中实例化对象后调用setTable。真的行。代码如下:publicfunctiondetail(){return$this->myHasOne(Circle::class,'group_id','group_id','t_group_'.hashID($this->userid,20));}public函数myHasOne($related,$foreignKey=null,$localKey=null,$table){$foreignKey=$foreignKey?:$this->getForeignKey();$instance=(new$related)->setTable($table);$localKey=$localKey?:$this->getKeyName();returnnewHasOne($instance->newQuery(),$this,$instance->getTable().'.'.$foreignKey,$localKey);}不知道有没有人有更优雅的方法。(原文地址:https://blog.tanteng.me/2018/...)
