Laravel Global Areas and Associations

I have a global setting in Laravel 5.1, which works fine. However, on some of my pages I use MySQL joins using the Eloquent constructor. This leads to an ambiguous error:

 Column 'cust_id' in where clause is ambiguous 

I am not sure how to avoid this problem. I know that I can use subqueries instead, but is there another 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(); } } 
+5
source share
1 answer

To find out the field, you must 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()); } } 
+9
source

All Articles