laravel - 我在关系中使用 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` 为空)”
解决方案
如果要从关系中获取某些字段,则必须在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);
}
推荐阅读
- laravel - spatie/sitemap 不会安装在 Godaddy 服务器上的 laravel8 中
- rest - Flutter 转换数据 Iso8601
- python - 当我在函数中使用 dateutil.parser.parse() 时,它返回一个列表而不是 datetime 对象?
- javascript - 在消息中获取所有被 ping 的用户,然后检查他们是否都有角色
- javascript - masonry (macy.js) 不适用于 ie 11。它在触发“检查模式”后工作
- android-studio - Android Studio 输入/退格键不起作用
- android - Android AOSP 构建错误 mkbootimg --kernel out/target/product/xiaomi/kernel 而不是 mkbootimg --kernel out/target/product/xiaomi/boot.img
- python - Python:如何使用 pandas 错误保护读取 csv/xlsx 文件
- javascript - 显示表格后如何停止添加表格
- ffmpeg - 找不到用于在视频中添加水印的 FFMPEG 覆盖