Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.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 4::返回模型及其关系_Php_Json_Laravel - Fatal编程技术网

Php Laravel 4::返回模型及其关系

Php Laravel 4::返回模型及其关系,php,json,laravel,Php,Json,Laravel,我想返回模型及其部分关系 例:: 用户模型 public function comments() { return $this->hasMany('comments'); } 评论模型 public function user() { return $this->belongsTo('user'); } 我可以返回所有评论以及与评论相关联的用户名吗? 理想的效果是 $comment = Comments::find($id); $comment

我想返回模型及其部分关系

例::

用户模型

public function comments() 
{
    return $this->hasMany('comments');
}
评论模型

public function user() 
{
    return $this->belongsTo('user');
}
我可以返回所有评论以及与评论相关联的用户名吗?

理想的效果是

    $comment = Comments::find($id);
    $comment->user;
    return $comment;
这将返回一条注释和关联的用户完整模型。我只需要用户的名字。如果我调用
Comments::all()


提前谢谢。

您正在寻找雄辩的

假设您的评论模型有一个方法
user()

您应该能够在控制器中执行此操作:

$comments = Comments::with('user')->where('post_id', $post_id);

// Return JSON, as is Laravel's convention when returning 
// Eloquent model directly
return $comments;
您也可以做相反的事情:

假设您的用户模型有一个方法“comments()”,如下所示:

public function comments()
{
    return $this->hasMany('Comment');
}
在控制器内部,假设您有可用的用户$id,您应该能够执行以下操作:

$user = User::with('comments')->find($id);

// Return JSON, as is Laravel's convention when returning 
// Eloquent model directly
return $user;
$user = User::with('comments')->find($id);

// Return JSON, as is Laravel's convention when returning 
// Eloquent model directly
return $user;