且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-02 20:51:28

您正在寻找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;