Laravel 5.1 Multitenancy setup

冷暖自知 提交于 2019-12-24 05:22:08

问题


I am using Laravel 5.1 and have a multi-tenancy database setup using a trait and scope as below. How can I add to this so that all insert queries also get the cust_id parameter injected?

Scope:

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

Trait:

<?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:


In order to do that, you'll need to override the default Eloquent Model's behaviour. You can modify one of the methods that participate in creating object or saving it.

My suggestion is to override the default creation behaviour logic as this will give you an object with custId set even before you save it to the database.

The easiest way to achieve that is to override the inherited constructor in a trait. In order to do that, add this method to your trait:

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


来源:https://stackoverflow.com/questions/32022783/laravel-5-1-multitenancy-setup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!