I have a litle problem implementing a HasManyThrough Relationship in my laravel project. It's basically a forum app :
We have ---USERS--- who can post ---REPLIES--- in various ---TOPICS---.
// USER MODEL
public function messages(): HasMany {
return $this->hasMany(Reply::class);
}
// TOPIC Model
public function replies(): HasMany {
return $this->hasMany(Reply::class);
}
// REPLY Model
public function topic(): BelongsTo {
return $this->belongsTo(Topic::class);
}
public function user(): BelongsTo {
return $this->belongsTo(User::class);
}
A relation between Replies and Replies exists too : a user can reply to a previous message which was posted by another user
// REPLY Model
public function parent_reply(): BelongsTo {
return $this->belongsTo(Reply::class, 'parent_reply_id', 'id');
}
public function children_replies(): HasMany {
return $this->hasMany(Reply::class, 'parent_reply_id', 'id');
}
Now, my problem is to create the HasManyThrough relationship which can allow me getting all the message which are answering a specific user's own message.
For example, John post 2 messages : message1 and message 2.
5 users answered to message1, and 3 users answered on message2.
=> I need the relation which give me those 8 answered messages to John. I try this :
// User Model
public function replies() {
return $this->hasManyThrough(
Reply::class,
Reply::class,
'user_id',
'parent_reply_id',
'id',
'id'
);
}
But I have this error when I test it :
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'replies'
select
replies.*,replies.user_idaslaravel_through_keyfromrepliesinner joinrepliesonreplies.id=replies.parent_reply_idwherereplies.user_id= 3
I dont' understand the Not unique table/alias: 'replies' and how to solve it.
If someone could help me, it would be very great :)
Thanks to the community !