gpt4 book ai didi

php - 如何在 Laravel Eloquent 中通过预加载按键索引返回的数组?

转载 作者:行者123 更新时间:2023-11-29 01:16:19 29 4
gpt4 key购买 nike

我正在做一个副项目,我们正在尝试为用户的帖子实现“赞”功能。我们正在使用 Laravel 的 ORM,我们希望使用预先加载来使事情变得更容易,我将在下面概述这个问题。首先是一些信息,Post.php 模型包含以下内容:

public function likes()
{
return $this->hasMany('App\Models\PostLike', 'post_id', 'post_id');
}

实现 API 调用以加载帖子及其喜欢的 PostController.php 看起来像:

$posts = Post::with("likes")->where("group_id", "=", $group_id)->get();

来自帖子 API 的示例 JSON 响应可能如下所示:

[
{
"post_id":1,
"group_id":1,
"author_id":1,
"text":"Some text here.",
"created_at":"2015-08-13 00:15:08",
"updated_at":"2015-08-13 00:15:08",
"likes":[
{"post_id":1,"user_id":1,"updated_at":"2015-08-14 03:05:48"}
]
}
]

这个问题是“喜欢”不是由 user_id 索引的,因此您必须搜索数组以确定用户是否喜欢该帖子,将其索引为 user_id 会容易得多唯一的 user_id 键。那会产生类似的东西:

[
{
"post_id":1,
"group_id":1,
"author_id":1,
"text":"Some text here.",
"created_at":"2015-08-13 00:15:08",
"updated_at":"2015-08-13 00:15:08",
"likes":{
"1": {"post_id":1,"user_id":1,"updated_at":"2015-08-14 03:05:48"}
}
}
]

所以最终的问题是我们如何通过它返回的列之一索引预加载响应?

最佳答案

为了实现这一点,您需要在代码中添加额外的后处理步骤,以通过 id 对数组进行索引。使用 Collection 的辅助方法 keyBy() 非常容易。

您需要的是一个访问器,它可以在需要时加载关系并重新索引数组。这个访问器可以在不同的场景中使用,即使没有预先加载关系,这就是为什么它需要在需要时处理关系加载。

将该方法添加到您的 Post 模型应该可以解决问题:

public function getLikesAttribute() {
return $this->getRelationValue('likes')->keyBy('user_id');
}

在这种情况下,当存在 botu likes()getLikesAttribute() 时,自定义访问器优先于关系定义。这就是为什么当您执行 $post->likes 时将调用您的访问器并将重新索引表。

关于php - 如何在 Laravel Eloquent 中通过预加载按键索引返回的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32038019/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com