laravel-5 - 如何使用 laravel eloquent 连接 3 个表

标签 laravel-5 model eloquent relation

如何在 Laravel 5 中应用此查询? 我有 3 个表,帖子、个人资料、评论

Post{id,title,body,user_id}
profile{user_id,last_name,first_name}
comments{comments,user_id,post_id}

我想要得到这种结构:

post_id 标题 帖子姓氏 名字

下面是评论

评论姓氏拳头名

最佳答案

//发布模型

public function comments(){
    return $this->hasMany('App\Comments', 'post_id', 'id');
}

//评论模型

public function user(){
    return $this->belongsTo('App\Profile', 'user_id');
}

//配置文件模型

public function comments(){
    return $this->hasMany('App\Comments');
}

我在 Controller 中使用以下方式调用它:

$posts = Posts::with('userProfile','comments', 'comments.user')->get();

然后就可以了:) 感谢您的一些帮助和想法:)

关于laravel-5 - 如何使用 laravel eloquent 连接 3 个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30949650/

相关文章:

mysql - Laravel Eloquent : Alphabetical Order but from Small words to Sentence

php - 如何正确使用laravel-dompdf生成view的pdf

laravel - 当我们在 Laravel 中将 SESSION_DRIVER/CACHE_DRIVER 设置为 redis 时,过期时间是多少?

php - Laravel session 没有破坏

wpf - MVVM 模型实例化

validation - ExtJS 4 中的 RowEditor 数据验证

laravel-5 - 急切加载 hasMany & BeingsTo(循环引用/无限循环)

php - `setAppends([])` 位于 Laravel 中由 `with` 加载的关系上

php - 用Mysql将相同的内容 "type"存储在一张表中

mysql - 类似的使用 Laravel 4/5 中的 QueryBuilder 或 Eloquent 查询 SQL