
在实际开发中经常用到分库分表,比如用户表分成 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,果然可以。
百灵大模型
蚂蚁集团自研的多模态AI大模型系列
177 查看详情
代码如下:
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模型间关系设置分表方法详解的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/357383.html
微信扫一扫
支付宝扫一扫