Laravel 4:: Returning models and its relationship

拜拜、爱过 提交于 2021-02-19 04:17:54

问题


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()

Thank you in advance.


回答1:


You're looking for Eloquent's Eager Loading

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:

Assuming your User model has a method 'comments()', like so:

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:

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

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


来源:https://stackoverflow.com/questions/17508448/laravel-4-returning-models-and-its-relationship

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!