【发布时间】:2019-08-10 00:03:20
【问题描述】:
我使用 Laravel。
我在 post 和 cmets 之间有关系。
我有$post,我想获得相关的$comments,只有值published 设置为true。
在控制器中我有:
$post = Post::find($id);
$comments = $post->comments->where('published', 1)->get();
这里的变量comments 看起来很正常,但是当我这样做时:
return [
'comments' => $comments,
'post' => $post,
];
我有来自 db 的所有 cmets,并在一个数组中与 cmets 进行连接。 例如
$post:
id 24
title "lorem"
body "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis explicabo molestias obcaecati placeat vero. Alias aliquid consectetur, deserunt ducimus iure magnam minus molestias neque pariatur quidem sint temporibus totam vitae."
user_id 2
published 1
created_at "2018-12-03 12:14:30"
updated_at "2019-03-29 10:08:26"
comments [
1 [ ... ]
2 [ ... ]
n [ ... ]
]
$comments {
1 [ ... ]
2 [ ... ]
n [ ... ]
}
那么我在哪里做错了?为什么会变?
model Comment.php
public function post()
{
return $this->belongsTo(Post::class);
}
public function scopePublished($query)
{
return $query->where('published', 1);
}
Post.php
public function comments()
{
return $this->hasMany(Comment::class);
}
【问题讨论】:
-
你为什么不使用
eager-loading?你可以查看我的帖子 -
在我得到 cmets 之前,我已经有帖子了。我展示了我的逻辑的简化版本:D