首页 > 解决方案 > 我在关系中使用 select 语句时遇到问题,如何在此语句中选择 images.path 列

问题描述

try {
        $products = $this->productRepo->with(['images'])->select('products.name', 'products.price', 'images.path')->where('category_id', $categoryId)->get();
        dd($products->toArray());
        return response()->json($products, 200);
    } catch (\Throwable $th) {
        $messager = $th->getMessage();
        return response()->json($messager, 404);
    }

“SQLSTATE [42S22]:未找到列:1054 '字段列表'中的未知列'images.path'(SQL:选择`products`.`name`、`products`.`price`、`images`.`path`来自 `products`,其中 `category_id` = 1 和 `products`.`deleted_at` 为空)”

这是我在模型图像中使用 l5repository(模型产品)声明关系的代码

标签: laravelselecteloquent

解决方案


如果要从关系中获取某些字段,则必须在with方法中实现查询:

    try {
        $products = $this->productRepo->with(['images' => function($query) {
            $query->select(['path']);
        }])->select(['name', 'price'])->where('category_id', $categoryId)->get();
        dd($products->toArray());
        return response()->json($products, 200);
    } catch (\Throwable $th) {
        $messager = $th->getMessage();
        return response()->json($messager, 404);
    }

推荐阅读