solutosoft/

yii-multitenant

所有租户共用的数据库

1.1.0 2020-02-20 12:05 UTC

This package is auto-updated.

Last update: 2024-08-27 00:07:47 UTC


README

此扩展为ActiveRecord MultiTenant提供支持。

Build Status Scrutinizer Code Quality Code Coverage Total Downloads Latest Stable Version

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

php composer.phar require --prefer-dist solutosoft/yii-multitenant

或者添加

"solutosoft/yii-multitenant": "*"

用法

  1. 创建包含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(),
        ]);
    }
}
  1. 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]);
    }
    
    ...
    
}
  1. 通过从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);