2
我正在使用Laravel 5.1,並使用如下的trait
和scope
進行多租戶數據庫設置。我怎樣才能添加到這個,以便所有的插入查詢也得到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());
}
}
嗨 - 感謝這一點,但它會導致錯誤:'MassAssignmentException在Model.php行417:cust_id'。我需要在其他地方添加cust_id嗎? – V4n1ll4
它需要在$可填充數組 –
只需將其添加到$ fillable但仍然是相同的錯誤。 – V4n1ll4