How to create Scope in Laravel 5.4 with tables linked through belongsToMany

0

The structure of the table is this:

pessoa
   id - integer
   nome - string

unidade
   id - integer
   nome - string

pessoa_unidade
   pessoa_id - integer
   unidade_id - integer

I have the templates:

class Pessoa extends Model
{
    public function unidades()
    {
        return $this->belongsToMany('App\Unidade', 'pessoa_unidade');
    }
}

class Unidade extends Model
{
    public function pessoas()
    {
        return $this->belongsToMany('App\Pessoa', 'pessoa_unidade');
    }
}

That is, a person can join multiple units and one unit can have multiple people;

In the standard users table of Laravel we have:

users
   id - integer
   nome - string
   unidade_id - integer

Where each user has their unit.

[PROBLEM 1]

How to create a scope to search only the linked people of a given unit?

I tried using GlobalScope :

class UnidadeScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $model->unidades()->where('unidade_id', 1);
    }
}

class UnidadeScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $query->unidades()->where('unidade_id', 1);
    }
}

But I could not ... tried to use LocalScopes :

public function scopeUn($query, $unidade)
{
    return $query->unidades()->where('unidade_id', $unidade);
}

Unsuccessful ...

[PROBLEM 2]

Another point of this question is to have the option to send a variable to scope as in the example I made above in the local scope where I send the user unidade_id ($ unit) through of the controller , using Auth::user()->unidade_id; .

The expectation was that controller , Local Scope would return all persons linked to the logged-in user, as follows:

Pessoa::Un(Auth::user()->unidade_id)->get();

Has anyone ever implemented anything like this?

    
asked by anonymous 06.05.2017 / 12:49

1 answer

0

I got the help from our community as follows:

public function scopeUn($query, $unidade_id)
{
    $query->whereHas('unidades', function ($query) use ($unidade_id) {
        $query->where('pessoa_unidade.unidade_id', $unidade_id);
    });
}

Using:

Person::Un(Auth::user()->unidade_id)->get();

Source: link

    
08.05.2017 / 15:22