Reputation: 1783
I have a model for users
class User
{
protected $primaryKey = 'user_id';
public function blocks()
{
return $this->belongsToMany(Block::class, 'block_user', 'blocker_id', 'blocked_id')->withTimestamps();
}
}
And a model for blocks
class Block extends Model
{
protected $table = "block_user";
}
So I have two tables: one for user information and the other for when one blocks another(Pivot Table) so user_id
in users table is both local and foreign.
The problem is that when I want to get if user has blocked another user it returns an error saying: Syntax error or access violation: 1066 Not unique table/alias: 'block_user'
$user = User::where('user_id', 1)->first();
dd($user->blocks->first_name);
How can I fix it? Thanks
Upvotes: 0
Views: 3749
Reputation: 35337
You are relating the User model to the User model, not to the Block model. A model for a pivot table is not necessary and usually would never be used.
public function blocks()
{
return $this->belongsToMany(User::class, 'block_user', 'blocker_id', 'blocked_id')->withTimestamps();
}
So instead of relating to Block::class
in your belongsToMany, relate to User::class
.
Upvotes: 1