Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

laravel的模型嵌套关联问题

现在做的类似朋友圈的接口查询
用户表 user 文章表 article 评论表 comment 点赞表 zan 结构如下

class User extand Model {
    public function articles() {
        return $this->hasMany(Article::class, 'user_id', 'id');
    }
}

class Article extand Model {
    public function comments() {
        return $this->hasMany(Comment::class, 'article_id', 'id');
    }
}

class Article extand Model {
    public function zans() {
        return $this->hasMany(Zan::class, 'article_id', 'id');
    }
}

class Comment extand Model {
    public function user() {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}

class Zan extand Model {
    public function user() {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}

User::with('articles.comments.user')->where('id', 10)->get();

现在需求是根据用户 id 查询所有文章和文章下面的评论和点赞,评论、点赞里显示对应的用户信息。

User::with('articles.comments.user')->find(10);
`
上面只能查出一种,用 morphTo这种嵌套的没试出来,请问大家有没有高效的方法呢。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
User::with(['articles.comments.user','articles.zans.user'])->find(10);

这样是可以实现,但是效率是不是很低呢、


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...