rent_property(表名)
id fullName propertyName
1 A House Name1
2 B House Name2
3 C House Name3
4 D House Name4
rent_amenity(表名)
rentamenityId rentPropertyId amenityName
1 1 Lift
2 1 Gym
3 2 Power backup
4 4 Gym
我的SQL查询
$sql = "SELECT a.id,a.fullName,a.propertyName FROM rent_property a LEFT JOIN rent_amenity b ON a.id = b.rentPropertyId WHERE a.city='1' AND a.propertyType IN ( '1','2' ) AND b.amenityName IN ( 'Gym' ) AND a.approveStatus!='Inactive' GROUP BY a.id order by a.id desc";
$result = $this->GetJoinRecord($sql);
我的动态功能
public function GetJoinRecord($query_string){
$con = $this->DBConnection();
$query = mysqli_query($con,$query_string);
if(@mysqli_num_rows($query)>0){
while($data=mysqli_fetch_assoc($query)){
$record[] = $data;
}
mysqli_free_result($query);
}
mysqli_close($con);
return $record;
}
基于我的表和mysql查询我应该得到两条记录,而且我得到的正确,但我无法达到我的预期结果,请看下面我将发布目前我得到的结果什么是我的预期结果
当前输出
{
"status": "success",
"message": "Data Found.",
"data": {
"rent_id": [
{
"id": "4",
"fullName": "D",
"propertyName": "House Name4"
},
{
"id": "1",
"fullName": "A",
"propertyName": "House Name1"
}
]
}
}
我的预期结果
{
"status": "success",
"message": "Data Found.",
"data": {
"rent_id": [
{
"id": "4",
"fullName": "D",
"propertyName": "House Name4",
"amenities":[
{
"rentamenityId":"4",
"rentPropertyId":"4",
"amenityName":"Gym"
}
]
},
{
"id": "1",
"fullName": "A",
"propertyName": "House Name1",
"amenities":[
{
"rentamenityId":"1",
"rentPropertyId":"1",
"amenityName":"Lift"
},
{
"rentamenityId":"2",
"rentPropertyId":"1",
"amenityName":"Gym"
}
]
}
]
}
}
在这里,我想根据我的属性从我的第二个表( rent_amenity )添加设施数组(设施名称),我不知道如何推送设施记录在我的第一个阵列中。
答案 0 :(得分:0)
你会想要更接近以下的东西。
SELECT *
FROM rent_property a
LEFT JOIN rent_amenity b ON a.id = b.rentPropertyId
WHERE a.city='1' AND a.propertyType IN ( '1','2' )
/* AND b.amenityName IN ( 'Gym' ) -- Removed to return all properties */
AND a.approveStatus!='Inactive'
GROUP BY a.id order by a.id desc
但是,对于您的属性中的每个设施,这将返回一行,因此您必须处理每个属性并在循环遍历行时检索处理它的设施。
另一种选择是使用单个查询来检索属性,然后使用第二个查询来检索返回属性的设施。