当前位置: 移动技术网 > IT编程>开发语言>PHP > Laravel模型间关系设置分表的方法示例

Laravel模型间关系设置分表的方法示例

2018年04月28日  | 移动技术网IT编程  | 我要评论

eloquent是什么

eloquent 是一个 orm,全称为 object relational mapping,翻译为 “对象关系映射”(如果只把它当成 database abstraction layer 数组库抽象层那就太小看它了)。所谓 “对象”,就是本文所说的 “模型(model)”;对象关系映射,即为模型间关系。中文文档: http://laravel-china.org/docs/eloquent#relationships

引用

在实际开发中经常用到分库分表,比如用户表分成 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 函数的实现方法,没有地方可以设置表名,只好复制一份 hasone 方法进行修改。比如改成 myhasone,加上 $table 参数可以设置表名,并且在对象实例化后调用 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);
}

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网