Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel关于关系的雄辩复杂查询_Php_Mysql_Laravel_Eloquent - Fatal编程技术网

Php Laravel关于关系的雄辩复杂查询

Php Laravel关于关系的雄辩复杂查询,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,期望输出: Post uid comments uid author username likes uid username likes uid user username author uid user

期望输出:

Post
   uid
   comments
          uid
          author
             username
          likes
             uid
                username
   likes
          uid
          user
             username
   author
          uid
          user
             username
所以现在我有了所有的评论、喜欢的文章和作者。
但它们都只包含UID

这里:现在我想在评论、喜欢和作者中添加用户名信息,这样我就可以获得喜欢帖子和其他元素的用户的用户名或名字

把它分解

  • 每个帖子都包含帖子的详细信息、评论、喜欢的内容和作者
  • 当前注释中包含作者用户数据(正确)
  • 当前,评论中的用户数据包含化身id(错误,我想要化身链接)
  • 当前在likes中是user\u id(错误,我想要user\u数据)
  • 当前在作者内部是用户数据,但只有到化身的ID(错误,我想要从user_avatars表到化身的链接)
我的模特

/**
 * Author of a post.
 *
 * @return Object
 */
public function author()
{
    return $this->belongsTo('User', 'uid', 'uid');
}   

/**
 * Comments of a post.
 *
 * @return Object
 */
public function comments()
{
    return $this->hasMany('Post', 'reply_to', 'pid')->with('author');
}

/**
 * Likes of a post.
 *
 * @return Object
 */
public function likes()
{
    return $this->hasMany('Like', 'pid', 'pid');
}    
我的控制器

$post = Post::with('comments', 'likes', 'author')->where('jid', 2)->get();

return $post;

因此从技术上讲,Author()也应该加入到用户化身和文件中,因为用户化身包含文件ID和用户ID,文件表包含文件ID和到化身的链接。如何做?


另一个注意事项:“调用未定义的方法illumb\Database\Query\Builder::author()”
如果我这样做:

public function likes()
{
    return $this->hasMany('Like', 'pid', 'pid')->with('author');
} 

我遇到的问题与您面临的问题相同,我是这样解决的:

在您发布的模型中:

public function user()
{

    return $this->hasOne('User', 'uid', 'uid');

}
$post = Post::where('id', $id)->with('user')->first();
$post->user->firstname;
然后在您的post控制器中:

public function user()
{

    return $this->hasOne('User', 'uid', 'uid');

}
$post = Post::where('id', $id)->with('user')->first();
$post->user->firstname;
然后在你的贴片视图中:

public function user()
{

    return $this->hasOne('User', 'uid', 'uid');

}
$post = Post::where('id', $id)->with('user')->first();
$post->user->firstname;
当然,你也可以在你雄辩的陈述中添加评论和喜欢

让我知道这是否解决了您的问题。我可以将答案编辑成更好的解决方案