0
votes

I have two tables:

  1. Users:

id, first_name, last_name, email


  1. Employees

id, user_id, wage

There has a relationship between users and employees. The problem comes from when I have a scope inside the model:

public function scopeSearchPaginateAndOrder($query)
{
    $request = app()->make('request');

    return $query->whereHas('user.internal_companies', function ($company) {
            $company->where('companies.id', '=', \Session::get('current_company')['id']);
        })
        ->where(function ($query) use ($request) {
        })
        ->select(['user.first_name'])
        ->get();
}

I am getting the following error:

Unknown column 'user.first_name' in 'field list

However, the relationship does exist:

public function user()
{
    return $this->belongsTo('App\User', 'user_id');
}
1
can you try ->select('user.first_name')?Oluwafemi Sule

1 Answers

0
votes

I think the problem may be that your select is in the wrong place.

The idea of the scope is to add extra constraints to the underlying query builder for the object in question.

Try removing the select from the scope function and then using it after you have applied the scope. i.e.

public function scopeSearchPaginateAndOrder($query)
{

    return $query->whereHas('user.internal_companies', function ($company) {
            $company->where('companies.id', '=', \Session::get('current_company')['id']);
    });
}

$user = User::all()->searchPaginateAndOrder()->select('user.first_name')->get();

More documentation on the use global and local scopes can be found here:

https://laravel.com/docs/5.4/eloquent#query-scopes