首页 > PHP学习 > Laravel模型间关系设置分表方法详解

Laravel模型间关系设置分表方法详解

时间:2022年6月22日 分类:PHP学习 浏览量:232

在实际开发中经常用到分库分表,比如用户表分成 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);
}

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

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

标签: