使用数据透视从另一个表中获取所有记录

时间:2021-01-24 18:21:44

标签: laravel laravel-5

我有三张桌子:

评论

id

comment_links

id | comment_id | link_id

链接

id

我想获得与每个 Link 相关联的所有 Comment。如您所见,CommentLink 应该充当数据透视表,但我不知道如何设置关系以使其起作用。我想我需要使用 hasManyThrough relationship,但我不是 100% 确定。

以下是我目前的班级关系(可能有误):

Comment.php:

class Comment extends Model
{
    public function commentLinks()
    {
        return $this->hasMany('App\CommentLink', 'comment_id', 'id');
    }

    public function links()
    {
        // How do I fetch all links here using the pivot table?
    }
}

CommentLink.php:

class CommentLink extends Model
{
    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }
    
    public function link()
    {
        return $this->hasOne('App\Link', 'id', 'link_id');
    }
}

Link.php:

class Link extends Model
{
    public function commentLinks()
    {
        return $this->belongsToMany('App\CommentLink', 'link_id', 'id');
    }
}

我需要在这里做什么才能完成这项工作?

1 个答案:

答案 0 :(得分:0)

你的想法是对的,只是使用了错误的类名。

class Link extends Model
{
    public function comments()
    {
        return $this->belongsToMany('App\Comment');
    }
}

class Comment extends Model
{
    public function links()
    {
        return $this->belongsToMany('App\Link');
    }
}

您实际上不需要为数据透视表创建一个类,但如果需要,您可以。

这是关于如何执行此操作的非常好的指南。 https://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

相关问题