V4n1ll4
V4n1ll4

Reputation: 6099

Laravel global scopes and joins

I have a global scope setup in Laravel 5.1 which is working fine. However on some of my pages I am using MySQL joins using the Eloquent builder. This results in an ambiguous error:

Column 'cust_id' in where clause is ambiguous

I'm not sure how to avoid this problem. I know that I can use sub queries instead, but is there no other solution?

Here is my scope file:

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

Upvotes: 6

Views: 2290

Answers (1)

Ben Claar
Ben Claar

Reputation: 3415

In order to disambiguate the field, you should add the table name as a prefix:

public function apply(Builder $builder, Model $model)
{
    if($this->custId) 
    {
        $fullColumnName = $model->getTable() . ".cust_id";
        $builder->where($fullColumnName, $this->custId); 
    } 
    else 
    {
        $model = $builder->getModel();
        $builder->whereNull($model->getKeyName()); 
    }
}

Upvotes: 13

Related Questions