Laravel 中的模型关系

现在用户表 users ,文章表articles ,评论表comments。
现在是根据用户id查询所有文章和文章下面的评论,评论里显示对应的用户信息。

User::find(10)->articles() //这样能查询出对应的文章,后面的评论和对应评论的用户用什么方法可以有效的查出来放到一个数组里呢?
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案
class User extends Model {
    public function articles() {
        return $this->hasMany(Article::class, 'user_id', 'id');
    }
}

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

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

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

虽然可以这么做,但是不建议,建议按需加载,比如 Article 列表页只获取 Article 信息即可,进入某篇 Article 后再加载对应的 Comment 和 Comment 对应的 User。

4年前 评论
lovnie (楼主) 4年前
lovnie (楼主) 4年前
GeorgeKing (作者) 4年前
讨论数量: 2
class User extends Model {
    public function articles() {
        return $this->hasMany(Article::class, 'user_id', 'id');
    }
}

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

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

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

虽然可以这么做,但是不建议,建议按需加载,比如 Article 列表页只获取 Article 信息即可,进入某篇 Article 后再加载对应的 Comment 和 Comment 对应的 User。

4年前 评论
lovnie (楼主) 4年前
lovnie (楼主) 4年前
GeorgeKing (作者) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!