2013-07-07 85 views
3

我想回到它的關係模型和部分Laravel 4 ::迴歸模型及其關係

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

預先感謝您。

回答

6

你要找的雄辯的Eager Loading

假設您的評論模型的方法user()

public function user() 
{ 
    return $this->belongsTo('User'); 
} 

你應該能夠做到這一點在你的控制器:

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

// Return JSON, as is Laravel's convention when returning 
// Eloquent model directly 
return $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;