在实际开发中经常用到分库分表,比如用户表分成 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模型间关系设置分表方法详解的详细内容

更多学习内容请访问:

腾讯t3-t4标准精品php架构师教程目录大全,只要你看完保证薪资上升一个台阶(持续更新)

以上内容希望帮助到大家,很多phper在进阶的时候总会遇到一些问题和瓶颈,业务代码写多了没有方向感,不知道该从那里入手去提升,对此我整理了一些资料,包括但不限于:分布式架构、高可扩展、高性能、高并发、服务器性能调优、tp6,laravel,yii2,redis,swoole、swoft、kafka、mysql优化、shell脚本、docker、微服务、nginx等多个知识点高级进阶干货需要的可以免费分享给大家,需要的可以加入我的官方群点击此处。