SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias on relationship SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias on relationship laravel laravel

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias on relationship


Answered via the Larachat official Slack:

The relationship is missing a pivot table for this to work. The second argument in the participants method is the pivot table to use:

public function participants(){    return $this->belongsToMany('Namespace\Modules\Email\Models\Participant', 'PIVOT', 'message_id', 'user_id')->withTimestamps();}

Therefore, you can't use participants as the pivot because it is one of the tables in the relationship, you need a message_participant pivot table.


Your error is

...from `participants` inner join `participants` ...

You need to provide aliases for each reference, as in

...from `participants` p1 inner join `participants` p2 ...

and then use p1 and p2 in the correct places, for example

...on p1.`id` = p2.`user_id` ...

(I'm guessing on which is p1 and which is p2; you have to make that determination)


Answering this question for anyone who encountered this error much later.

Judging from your table records, the participants table seems to be the pivot table between users and messages. You are referencing the pivot table, leading to the database misbehaving.

The correct way to do this is in your users models:

public function messages(){   return $this->belongsToMany(Message::class, 'participants', 'user_id', 'message_id')->withPivot('last_read');}

In your messages models:

public function users(){   return $this->belongsToMany(User::class, 'participants', 'message_id', 'user_id')->withPivot('last_read');}

That way, when you calling messages from users, use this:

$messages = $user->messages()->get();

And when you checking the users for the message,

$user = $message->users()->get()

And last read

$last_read = $message->pivot->last_read;