Laravel 多层次关系

Laravel multiple levels relationships

我被人际关系问题困住了 这是我的数据库:

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

在我的用户中 class

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

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

但是当我尝试访问对话时出现错误。

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) 

我试过了

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

但结果并不是很好,我不确定这是做这件事的好方法!

感谢您的帮助

根据官方Laravel documentation;

Typical Eloquent foreign key conventions will be used when performing the relationship's queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the hasManyThrough method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model:

您需要根据您的外键自定义您的conversations方法。

这不是 hasManyThrough 关系结构,也不是 hasMany

这是一个 belongsToMany 关系,但不是你有一个 conversation_user table,你将它命名为 participants 试试这个:

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

第二个参数 'participants' 用于覆盖预期的 table 名称,即 'conversation_user'。我建议在文档中阅读更多相关信息。 https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

顺便说一句,您缺少对话 table 的 ID,但我想您有它,因为您有 conversation_id 参与者。