小编ali*_*r49的帖子

如何使用Laravel Eloquent中的急切加载按键索引返回的数组?

我正在开展一个侧面项目,我们正在尝试为用户的帖子实现"喜欢"功能.我们正在使用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)

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

php mysql laravel eloquent laravel-5

2
推荐指数
1
解决办法
1363
查看次数

标签 统计

eloquent ×1

laravel ×1

laravel-5 ×1

mysql ×1

php ×1