【发布时间】:2018-11-25 21:04:31
【问题描述】:
我正在构建一个 [post, cmets] 项目,其中帖子详细信息存储在帖子表中,评论详细信息存储在 cmets 表中。该项目是在 Laravel(Php) 中生成的。这是一段代码。
//get data from Post table
$posts = $this->postsRepo->getAllPosts();
//get data from comments table
$comments = $this->commentRepo->getAllComments();
print_r($posts);
print_r($comments);
post 表的结果
Array
(
[0] => stdClass Object
(
[id] => 1
[post_text] => This is a test post
)
)
[1] => stdClass Object
(
[id] => 2
[post_text] => This is another test
)
)
cmets 表的结果
Array
(
[0] => stdClass Object
(
[id] => 1
[post_id] => 1
[comments_text] => This is a test comment 1
)
[1] => stdClass Object
(
[id] => 2
[post_id] => 1
[comments_text] => This is a test comment 2
)
)
现在我想要类似的结果
Array
(
[0] => stdClass Object
(
[id] => 1
[post_title] => This is a test post
[comments] => Array
(
[0] => stdClass Object
(
[id] => 1
[post_id] => 1
[comment_text] => This is a test comment 1
)
[1] => stdClass Object
(
[id] => 2
[post_id] => 1
[comment_text] => This is a test comment 2
)
)
)
)
[1] => stdClass Object
(
[id] => 2
[post_title] => This is another test
[comments] => Array()
)
)
我使用了以下技术,它正在工作
foreach ($posts as $postIndex => $post) {
foreach ($comments as $commentIndex => $comment) {
if($post->id == $comment->post_id) {
$posts[$postIndex]->comments[] = $comment;
}
}
}
还有另一种方法,例如在 post for 循环中运行 cmets。我会将 post_id 发送到 cmets 表。但是随着数据的增加,这种技术会很慢
有人可以提出更好的技术来解决这个问题吗? 另外,我使用 Repository 设计模式来获取帖子和 cmets
【问题讨论】:
-
为什么不使用 laravel 关系? laravel.com/docs/5.6/eloquent-relationships
-
在您的 Post Model 中定义关系并命名 cmets 更改您的查询 PostModel::with('cmets')->get();
-
我没有使用 Eloquent。使用简单的数据库查询
-
你使用的是什么版本的 PHP?
-
放弃 repo 设计模式并使用 eloquent。它做同样的事情,并且已经为您提供了执行此操作的代码。
标签: php arrays laravel for-loop