温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Laravel模型间关系设置分表

发布时间:2021-01-27 14:22:10 来源:亿速云 阅读:179 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关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模型间关系设置分表”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI