php - 如何从关系中检索数据?

标签 php

发布模型

class Post extends Model
{


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

    public function users()
    {
        return $this->belongsTo('App\User');
    }

评论模型

class Comment extends Model
    {

    public function posts()
    {
        return $this->belongsTo('App\Post');
    }


   }  

用户模型

class User extends Model
{


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

现在我的问题是如何访问属于带有评论用户名的帖子的所有评论 预先感谢您

最佳答案

试试这个,它将返回所选用户的所有带有评论的帖子以及带有作者的帖子。

$data = User::with('post.comment') 
        -> with('post.author') 
        -> Where('id',$user_id) 
        -> first();

这将获取作者的帖子以及发表评论的用户的评论。 假设您的模型是这样设置的,

Post belongs to an Author,   
Author has many Post,  
Post has many Comment  
Comment belongs to a Post  
Comment belongs to a User  
User has many Comment.   

$posts = Post::with('author') -> with('comment.user') -> get(); 

关于php - 如何从关系中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32391723/

相关文章:

php - 使用pdo在两个mysql表中插入一条记录

php - 注销 PHP 脚本

php - 通过 jquery 无意中发布了多个帖子

php - 是否可以将当前登录用户的 ID 与 php 表单一起添加?

PHP 如何在 aws s3 存储桶中创建文件夹?

php - 如何在 centos 6.x 中安装 php-pear-Net-SMTP?

php - 使用 PHP 备份数据库

php - doctrine 2 和 zend framework 2 如何使用缓存?

php - 如果复制数据,再次mysql_real_escape_string?

PHP 提交按钮不起作用。