ali*_*r49 2 php mysql laravel eloquent laravel-5
我正在开展一个侧面项目,我们正在尝试为用户的帖子实现"喜欢"功能.我们正在使用Laravel的ORM,我们希望使用急切加载来简化操作,我将在下面概述问题.首先是一些信息,Post.php模型包含:
public function likes()
{
return $this->hasMany('App\Models\PostLike', 'post_id', 'post_id');
}
Run Code Online (Sandbox Code Playgroud)
实现API调用以加载帖子及其喜欢的PostController.php看起来像:
$posts = Post::with("likes")->where("group_id", "=", $group_id)->get();
Run Code Online (Sandbox Code Playgroud)
posts 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"}
]
}
]
Run Code Online (Sandbox Code Playgroud)
这个问题是"喜欢"没有被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"}
}
}
]
Run Code Online (Sandbox Code Playgroud)
所以最终的问题是我们如何通过它返回的一个列来索引热切的加载响应?
为了实现这一点,您需要为代码添加额外的后处理步骤,以便通过id索引数组.使用Collection的辅助方法keyBy()非常容易.
你需要的是一个访问器,它会在需要时加载关系并重新索引数组.这个访问器可以在不同的场景中使用,即使没有急切地加载关系,这就是它需要处理关系加载的原因.
将该方法添加到Post模型应该可以解决这个问题:
public function getLikesAttribute() {
return $this->getRelationValue('likes')->keyBy('user_id');
}
Run Code Online (Sandbox Code Playgroud)
在存在botu likes()和getLikesAttribute()的情况下,自定义访问器优先于关系定义.这就是为什么当你执行$ post-> likes时会调用你的访问者并重新索引表的原因.
| 归档时间: |
|
| 查看次数: |
1363 次 |
| 最近记录: |