您好,欢迎来到舟格财经。
搜索
您的当前位置:首页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);
}

不知道大家有没有更优雅的方式。

Copyright © 2019- zougedi.com 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务