Laravel 5.1多租户设置

时间:2015-08-15 08:04:07

标签: php laravel laravel-5 eloquent

我正在使用Laravel 5.1并使用traitscope进行多租户数据库设置,如下所示。如何添加到此以便所有插入查询也都会注入cust_id参数?

范围:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ScopeInterface;
use App\Customers;
use DB, Session;

class MultiTenantScope implements ScopeInterface
{
    /**
     * Create a new filter instance.
     *
     * @param  UsersRoles $roles
     * @return void
     */
    public function __construct()
    {
        $this->custId = Session::get('cust_id');
    }

    /**
     * Apply scope on the query.
     *
     * @param Builder $builder
     * @param Model $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        if($this->custId) 
        {
            $builder->where($model->getTable() . '.cust_id', $this->custId); 
        } 
        else 
        {
            $model = $builder->getModel();
            $builder->whereNull($model->getKeyName()); 
        }
    }

    /**
     * Remove scope from the query.
     *
     * @param Builder $builder
     * @param Model $model
     * @return void
     */
    public function remove(Builder $builder, Model $model)
    {
        $query = $builder->getQuery();
        $query->wheres = collect($query->wheres)->reject(function ($where) 
        {
            return ($where['column'] == 'cust_id');
        })->values()->all();
    }  
}

特点:

<?php 

namespace App\Scopes;

trait MultiTenantTrait
{
    /**
     * Boot the scope.
     * 
     * @return void
     */
    public static function bootMultiTenantTrait()
    {
        static::addGlobalScope(new MultiTenantScope());
    }

    /**
     * Get all tenants.
     * 
     * @return string
     */
    public static function allTenants()
    {
        return (new static())->newQueryWithoutScope(new MultiTenantScope());
    }
}

1 个答案:

答案 0 :(得分:2)

为此,您需要覆盖默认的Eloquent Model的行为。您可以修改参与创建对象或保存对象的方法之一。

我的建议是覆盖默认的创建行为逻辑,因为即使在将其保存到数据库之前,也会为您提供 custId 设置的对象。

实现这一目标的最简单方法是覆盖特征中的继承构造函数。为此,请将此方法添加到您的特征中:

public function __construct(array $attributes = [])
{
  parent::__construct(array_merge($attributes, ['cust_id' => $this->custId]));
}