我想知道如何从3个表创建关系。
这是我的模型结构:
用户模型
class User extends Eloquent {
public function Posts(){
return $this->hasMany('Post');
}
public function comments(){
return $this->hasMany('comment');
}
}
class Post extends Eloquent {
public function comments() {
return $this->hasMany('Comments');
}
public function user(){
return $this->belongsTo('user');
}
}
class Comments extends Eloquent {
public function user(){
return $this->belongsTo('user');
}
public function Post(){
return $this->belongsTo('Post');
}
}
用户可以有多个帖子,每个帖子都有用户的多条评论。
我试图从发表评论的用户的帖子中抓取所有评论
$comments = Post::find(1)->comments()->get();
foreach ($comments as $comment) {
// here my code now to get the user
$comment->user()->get()
}
结果:[
{
id: "1",
post_id: "1",
user_id: "1",
reply_text: "Testing",
},...
]
我认为这一点效率都没有。
我怎样才能使它更简单呢?
[
{
id: "1",
post_id: "1",
user_id: "1",
reply_text: "Testing",
user_post: {
id: 1,
name: "Edi vianika",
profil_img: "l.jpg"
}
}
]
Phill在评论中正确回答了这个问题,正如他所说,你应该使用Eager Loading。
$post = Post::with('comments', 'comments.user')->find(1);
那么你可以简单地像这样迭代:
foreach ($post->comments as $comment) {
echo $comment->user->name . ' said: ' . $comment->title;
}
为了清楚起见,我建议您将您的$comment->user
关系命名为author
,而不是将其命名为$comment->author->name
感觉很自然。您可以这样做:
class Comments extends Eloquent {
public function author()
{
return $this->belongsTo('user', 'user_id');
}
}
// Remember to change eager loading to 'comments.author'