Laravel多层次关系

Adfop

我在关系上遇到问题,这是我的数据库:

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

在我的用户类别中

    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');
    }

但是结果不是很好,我不是那是这样做的好方法!

感谢您的帮助

埃鲁比尔

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

那是一个belongsToMany关系,但是您不用拥有一个对话用户表,而是将其命名为参与者,请尝试以下操作:

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

第二个参数'participants',用于覆盖预期的表名'conversation_user'我建议在文档上阅读更多有关它的内容。https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

顺便说一句,您在对话表上缺少一个ID,但是我想您有它,因为您在参与者上有session_id。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章