Laravel 4:: 返回模型及其关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17508448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4:: Returning models and its relationship
提问by 2557272
I would like to return the model and part of its relationship
我想返回模型及其部分关系
EX::
前任::
User model
用户模型
public function comments()
{
return $this->hasMany('comments');
}
Comments model
评论模型
public function user()
{
return $this->belongsTo('user');
}
Can I return all comments and the user's name associated with the comment?
我可以返回所有评论以及与评论相关的用户名吗?
The desired effect is
想要的效果是
$comment = Comments::find($id);
$comment->user;
return $comment;
This will return the one comment and the associated user full model. I just need the name of the user. And this does not works if I call Comments::all()
这将返回一条评论和关联的用户完整模型。我只需要用户的名字。如果我打电话,这不起作用Comments::all()
Thank you in advance.
先感谢您。
回答by fideloper
You're looking for Eloquent's Eager Loading
您正在寻找 Eloquent 的Eager Loading
Assuming your Comments model has a method user()
:
假设您的 Comments 模型有一个方法user()
:
public function user()
{
return $this->belongsTo('User');
}
You should be able to do this in your controller:
您应该能够在控制器中执行此操作:
$comments = Comments::with('user')->where('post_id', $post_id);
// Return JSON, as is Laravel's convention when returning
// Eloquent model directly
return $comments;
You can do the opposite as well:
你也可以做相反的事情:
Assuming your User model has a method 'comments()', like so:
假设您的 User 模型有一个方法“comments()”,如下所示:
public function comments()
{
return $this->hasMany('Comment');
}
Inside of your controller, you should be able to do the following, assuming your have the $id of the user available:
在您的控制器内部,您应该能够执行以下操作,假设您拥有可用的用户 $id:
$user = User::with('comments')->find($id);
// Return JSON, as is Laravel's convention when returning
// Eloquent model directly
return $user;