2015-08-15 149 views
2

我正在使用Laravel 5.1,並使用如下的traitscope進行多租戶數據庫設置。我怎樣才能添加到這個,以便所有的插入查詢也得到cust_id參數注入?Laravel 5.1多租戶設置

範圍:

<?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()); 
    } 
} 

回答

2

爲了做到這一點,你需要覆蓋默認雄辯模型的行爲。您可以修改參與創建對象或保存對象的方法之一。

我的建議是重寫默認的創建行爲邏輯,因爲這會在您將其保存到數據庫之前設置爲custId

最簡單的方法是覆蓋特徵中的繼承構造函數。爲了做到這一點,這種方法添加到您的特點:

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

嗨 - 感謝這一點,但它會導致錯誤:'MassAssignmentException在Model.php行417:cust_id'。我需要在其他地方添加cust_id嗎? – V4n1ll4

+0

它需要在$可填充數組 –

+0

只需將其添加到$ fillable但仍然是相同的錯誤。 – V4n1ll4