关于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框架相关技术文章,请访问laravel教程栏目!

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享