我首先从表'properties'获取属性,然后运行内部查询以从单独的表'property_images'获取图像。这是一个缓慢的方法。指导我如何在api请求中的单个查询中获取属性和图像?
public function searchProperty(Request $request){
if(count($request->all()) > 0){
$properties = array();
$properties = \DB::table('properties')
->where($request->all())
->get()->toArray();
$prop_ids = array();
if(isset($properties) && !empty($properties) && count($properties) > 0){
foreach($properties as $prop){
array_push($prop_ids, $prop->id);
}
$prop_images = \DB::table('property_images')
->whereIn('property_id', $prop_ids)
->get()->toArray();
if(isset($prop_images) && !empty($prop_images)){
foreach($prop_images as $imgs){
$upload_path = storage_path() . '/uploads/property/' . $imgs->property_id .'/'.$imgs->property_image;
array_push($properties, $upload_path);
}
}
echo '<pre>'; print_r($properties); exit;
return response()->json([
'success' => true,
'data' => $properties->toArray()
], 400);
}
}
else{
return response()->json([
'success' => false,
'message' => 'No data available'
], 500);
}
}
答案 0 :(得分:0)
尝试此查询,它必须对您有用,以便仅通过单个查询即可获取所有属性及其所有图像。图片将以逗号分隔,您将在单个产品行中看到它。您必须以逗号爆炸。如果您编写任何api,都可以用图像连接完整的url。
DB::table('properties')
->selectRaw('GROUP_CONCAT(property_images.property_image) as
property_images, properties.*')
->leftJoin('property_images', 'property_images.property_id', '=', 'properties.id')
->groupBy('properties.id')
->get()->toArray();