众所周知 laravel 是 php 开发项目最优美的框架之一,尤其是 eloquent 对数据库的操作提供了特别多的便利。
在实际开发中我们经常涉及到分库分表场景,那么怎样才能继续配合 eloquent 优雅的使用 model 模型呢,接下来给大家分享下我在实际开发中所遇到的问题。(备注:此方法来源 stack overflow 原文地址找不到了,配合我们实际项目更能清晰表述)
1、假设我们有一万本书籍,每本书籍有两千章节,我们创建数据库时的表结构是书籍信息表:books;以及章节信息表:chapters,前面说到书籍越多章节数也就越多解决方案是将章节表分成十个形式为 chapters_0、chapters_1、……chapters_9 表后缀规则是书籍 id 与 10 取余,这样所有的书籍章节会分散在这 10 个 chapters 中。
2、表建好后开始创建 model 模型,按照惯例所有的模型都将写在 app\models 下;首先我们先创建一个类名为 model 的模型并继承 illuminate\database\eloquent\model
<?php namespace app\models; use illuminate\database\eloquent\model as eloquentmodel; class model extends eloquentmodel { protected $suffix = null; // 设置表后缀 public function setsuffix($suffix) { $this->suffix = $suffix; if ($suffix !== null) { $this->table = $this->gettable() . '_' . $suffix; } } // 提供一个静态方法设置表后缀 public static function suffix($suffix) { $instance = new static; $instance->setsuffix($suffix); return $instance->newquery(); } // 创建新的"chapters_{$suffix}"的模型实例并返回 public function newinstance($attributes = [], $exists = false) { $model = parent::newinstance($attributes, $exists); $model->setsuffix($this->suffix); return $model; } }
2、其他模型全都继承以上的 model 而不是继承 illuminate\database\eloquent\model,获取某本书的章节 controller
<?php namespace app\http\controllers; use app\models\{book, chapter}; class chapterscontroller extends controller { public function chapter (book $book) { // 章节列表(普通查询) $list = chapter::lists($book->id); // 章节列表(使用模型关联) $list = $book->chapters()->oldest('id')->get(); } }
3、chapter 模型(普通查询)
<?php namespace app\models; class chapter extends model { public static function lists ($bookid) { $suffix = $bookid % 10; /* * 例如 $sufiix = 1; 我要要获取的就是:chapters_1的模型实例 * 使用model类中提供的静态方法创建该表的模型实例 * 返回指定书籍的章节 */ return self::suffix($suffix)->where('book_id', $bookid)->get(); } }
3、好了,我们章节的分表模型已经完成了。那么如何使用模型关联呢?我们来看 book 模型如何关联 chapter
<?php namespace app\models; use illuminate\database\eloquent\relations\hasmany; class book extends model { public function chapters () { /* * books表的id和chapters表中的book_id关联 * 一对多关系(一本书对应多条章节) */ $instance = new chapter(); $instance->setsuffix($this->id % 10); $foreignkey = $instance->gettable . '.' . $this->getforeignkey(); $localkey = $this->getkeyname(); return new hasmany($instance->newquery(), $this, $foreignkey, $localkey); } }
到此 model 发表查询及 model 关联就完成了,如果有其他更好的方式,请大家不吝赐教。第一次发表文章,如有不对的地方希望大家多多指教!!也希望大家多多支持www.887551.com。
黄山市民网:https://www.huangshanshimin.com/