solutosoft / yii-multitenant
所有租户共用的数据库
1.1.0
2020-02-20 12:05 UTC
Requires
- yiisoft/yii2: ~2.0.16
Requires (Dev)
- phpunit/phpunit: ~4.4
This package is auto-updated.
Last update: 2024-08-27 00:07:47 UTC
README
此扩展为ActiveRecord MultiTenant提供支持。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令之一:
php composer.phar require --prefer-dist solutosoft/yii-multitenant
或者添加
"solutosoft/yii-multitenant": "*"
用法
- 创建包含
tenant_id
列的表
class m191023_101232_create_post extends Migration { /** * {@inheritdoc} */ public function up() { $this->createTable('post', [ 'id' => $this->primaryKey(), 'title' => $this->string()->notNull(), 'category_id' => $this->integer(), 'content' => $this->string() 'tenant_id' => $this->integer(), ]); $this->createTable('category', [ 'id' => $this->primaryKey(), 'name' => $this->string()->notNull(), 'tenant_id' => $this->integer(), ]); } }
- 将
TenantInterface
添加到用户模型
use solutosoft\multitenant\MultiTenantRecord; class User extends MultiTenantRecord implements IdentityInterface, TenantInterface { /** * {@inheritdoc} */ public function getTenantId() { return // logic to determine tenant from current user } /** * Finds user by username attribute * This is an example where tenant filter is disabled */ public static function findByUsername($username) { return static::find()->withoutTenant()->where(['username' => $username]); } ... }
- 通过从
MultiTenantRecord
扩展模型,而不是从ActiveRecord
扩展模型,添加tenant_id
属性
use solutosoft\multitenant\MultiTenantRecord; class Post extends MultiTenantRecord { ... } class Category extends MultiTenantRecord { ... }
现在,当你保存或执行某些查询时,将使用tenant_id
列。例如
// It's necessary the user will be logged in $posts = \app\models\Post::find()->where(['category_id' => 1])->all(); // SELECT * FROM `post` WHERE `category_id` = 1 and `tenant_id` = 1; $category = \app\models\Category([ 'name' => 'framework' ]); $category->save(); // INSERT INTO `category` (`name`, `tenant_id`) values ('framework', 1);