Error using Many to Many

Asked

Viewed 44 times

1

I have a group of Users who have relationship Many To Many, to create this relationship I did a function beLongsToMany within the model Usuarios. 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');
}

Calling for:

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

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

2 answers

1


You want to upload users and also people’s information, if so, use:

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

For you to use the function Pessoas you need to call it an instance of Usuarios, if you call the function first where you won’t be able to call the function Pessoas because the where returns an instance of Builder.

References:

0

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

In the 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 function belongsToMany receives 4 parameters we are using only 2 because I am assuming that its structure follows the pattern oriented by Laravel. For more information just check the documentation

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.