首页 > 解决方案 > Laravel 使用关系从 Query 中的 Array 获取单个项目

问题描述

在我的一个模型中,例如posts我有一个列数组featured_image,当我从这个模型获取返回所有这些数组项的结果查询时,例如:

"featured_image": {
    "images": {
        "original": "/uploads/post_images/2020/1598873165.jpg",
        "300": "/uploads/post_images/2020/300_1598873165.jpg",
        "900": "/uploads/post_images/2020/900_1598873165.jpg"
    },
    "thumbnail": "/uploads/post_images/2020/300_1598873165.jpg"
},

现在我如何修改下面的查询以从这个数组中只获取一个项目,例如thumbnail

public function allData()
{
    $posts = Post::with(['groups', 'categories' => function ($query) {
        $query->whereLocked(false);
    }])->wherePublished(true)->get();
    return response()->json([
        'posts' => $posts,
    ], 200);
}

标签: phplaravel

解决方案


你可以试试这个:

public function allData()
{
    $posts = Post::with(['groups', 'categories' => function ($query) {
        $query->whereLocked(false);
    }])->wherePublished(true)
    ->select('{primary must included to use With}', 'other', 'columns', 'featured_image->thumbnail as thumbnail')
    ->get();
    return response()->json([
        'posts' => $posts,
    ], 200);
}

推荐阅读