Search code examples
laraveleloquenteloquent-relationship

Laravel multiple levels relationships


I am stuck on a problem on relationships this is my database :

users table:
id
participants table:
user_id
conversation_id
conversations table:
name

In my user class

    public function participants() {
        return $this->hasMany(Participant::class);
    }

    public function conversations() {
        return $this->hasManyThrough(Conversation::class, Participant::class);
    }

But i have an error when I try to access conversations.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'conversations.participant_id' in 'on clause' (SQL: select `conversations`.*, `participants`.`user_id` as `laravel_through_key` from `conversations` inner join `participants` on `participants`.`id` = `conversations`.`participant_id` where `participants`.`user_id` = 1) 

I tried this

    public function conversations() {
        return $this->hasMany(Participant::class)->with('conversation');
    }

But the result is not really fine and I m not sur that's the good way to do it !

Thank you for your help


Solution

  • That is not a hasManyThrough relationship structure, neither a hasMany

    That's a belongsToMany relationship, but instead of you having a conversation_user table, you named it participants try this:

    public function conversations()
    {
        return $this->belongsToMany(Conversation::class, 'participants');
    }
    

    The second parameter 'participants', is for overriding the expected table name, which, would be 'conversation_user'. I recommend reading more about it on the docs. https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

    BTW, you are missing an id on the conversations table, but I suppose you have it because you have conversation_id on participants.