Error using many to many laravel

1

I have a group of Users that have Many To Many relationship, to create this relationship I made a beLongsToMany function within the Users model. But every time I call this function I get the following message:

  Uncaught exception 'BadMethodCallException' with message 'Call to undefined method Illuminate \ Database \ Query \ Builder :: People ()'

public function Pessoas(){
return $this->belongsToMany('entidades\Pessoas', 'pessoa_id');
}

Call:

Usuarios::where('usuario_id', $usuario_id)->Pessoas()->toSql();

For each of my users I want to get people's records.

    
asked by anonymous 20.09.2018 / 20:10

2 answers

1

You want to load users and also people's information, if it is, use:

Usuarios::where('usuario_id', $usuario_id)->with('Pessoas')->toSql();

For you to use the Pessoas function you need to call it from an instance of Usuarios , if you first call the where function you will not be able to call the Pessoas function because where returns an instance of the% Builder .

References:

20.09.2018 / 20:34
0

To define the relationship Many To Many it is necessary to have 3 tables, in your case it would be: users , people and user_user . The 3 table should follow the pattern of alphabetical order.

In Model of Users you should put the following:

public function pessoas() {
    return $this->belongsToMany( Pessoas::class, 'pessoa_usuario' ); // Primeiro parâmetro é o Model que você vai se relacionar e o segundo é o nome da tabela.
}

The belongsToMany function gets 4 parameters we're using only 2 because I'm assuming its structure follows the pattern driven by Laravel. For more information just check documentation

And to list all users who have the relationship you just need to use the following:

Usuarios::where('usuario_id', $usuario_id)->with('Pessoas')->get();
    
20.09.2018 / 20:44