Laravel 4 ::返回模型及其关系 [英] Laravel 4:: Returning models and its relationship
问题描述
我想返回模型及其部分关系
I would like to return the model and part of its relationship
EX ::
用户模型
public function comments()
{
return $this->hasMany('comments');
}
评论模型
public function user()
{
return $this->belongsTo('user');
}
我可以返回所有评论以及与该评论关联的用户名吗?
所需的效果是
$comment = Comments::find($id);
$comment->user;
return $comment;
这将返回一个注释和关联的用户完整模型.我只需要用户名.如果我拨打Comments::all()
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()
谢谢.
推荐答案
您正在寻找Eloquent的急切加载
You're looking for Eloquent's Eager Loading
假设您的评论模型具有方法user()
:
Assuming your Comments model has a method 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:
假设您的用户模型具有方法'comments()',如下所示:
Assuming your User model has a method 'comments()', like so:
public function comments()
{
return $this->hasMany('Comment');
}
在您的控制器内部,假设您有可用的用户$ id,您应该能够执行以下操作:
Inside of your controller, you should be able to do the following, assuming your have the $id of the user available:
$user = User::with('comments')->find($id);
// Return JSON, as is Laravel's convention when returning
// Eloquent model directly
return $user;
这篇关于Laravel 4 ::返回模型及其关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!