У меня есть 3 таблицы пригородов, свойства и изображения. Пригород является родительской таблицей
таблицы свойств в отношениях один ко многим, и изображение является дочерним
таблица свойств таблицы в отношении один ко многим.
Я хочу отображать одно изображение за раз по номеру пригорода, который будет отсортирован
(ORDER BY) по ID недвижимости.
После итерации все изображения отображаются корректно. Но я не могу
выяснить, как отображать каждую строку за раз, используя
идентификатор предместья (идентификатор родительской таблицы).
Ниже приведены контрольные примеры, в которых я пробовал разные решения:
Контрольный пример 1: итерация, отображающая все изображения
$query = "SELECT i.*, p.property_id, s.suburb_id
FROM property_images i
LEFT JOIN properties p
ON i.property_id = p.property_id
LEFT JOIN suburbs s
ON p.suburb_id = s.suburb_id
WHERE s.suburb_id = 60
ORDER BY p.property_id";
$result = $conn->query($query);
$images = array();
foreach($result as $row){
extract($row);
$images[] = $image_location . '<br />';
}
print_r($images);
/*
Output:
Array ( [0] => public/images/properties/uploads/1.jpg
[1] => public/images/properties/uploads/2.jpg
[2] => public/images/properties/uploads/3.jpg
[3] => public/images/properties/uploads/4.jpg
[4] => public/images/properties/uploads/5.jpg
[5] => public/images/properties/uploads/6.jpg
[6] => public/images/properties/uploads/7.jpg
[7] => public/images/properties/uploads/8.jpg
[8] => public/images/properties/uploads/9.jpg
[9] => public/images/properties/uploads/10.jpg
[10] => public/images/properties/uploads/11.jpg
[11] => public/images/properties/uploads/12.jpg
[12] => public/images/properties/uploads/13.jpg
[13] => public/images/properties/uploads/14.jpg
[14] => public/images/properties/uploads/15.jpg
[15] => public/images/properties/uploads/16.jpg
[16] => public/images/properties/uploads/17.jpg
[17] => public/images/properties/uploads/18.jpg
)
*/
Тестовый пример 2: сравнение $ image_id, если он равен эквивалентной строке
$query = "SELECT i.*, p.property_id, s.suburb_id
FROM property_images i
LEFT JOIN properties p
ON i.property_id = p.property_id
LEFT JOIN suburbs s
ON p.suburb_id = s.suburb_id
WHERE s.suburb_id = 60
ORDER BY p.property_id";
$counter = mysqli_num_rows($result);
$image_id = $row['property_image_id'];
$image_location = $row['image_location'];
if($counter > 0){
if($image_id == 1){
print_r($image_location);
}
}
//Here the first row is returned
/*
Output:
public/images/properties/uploads/1.jpg
*/
Тестовый пример 3: сравнение $ image_id, если оно равно номеру строки 2
$query = "SELECT i.*, p.property_id, s.suburb_id
FROM property_images i
LEFT JOIN properties p
ON i.property_id = p.property_id
LEFT JOIN suburbs s
ON p.suburb_id = s.suburb_id
WHERE s.suburb_id = 60
ORDER BY p.property_id";
$counter = mysqli_num_rows($result);
$image_id = $row['property_image_id'];
$image_location = $row['image_location'];
if($conter > 0){
if($image_id == 2){
print_r($image_location);
}
}
//Here it returns null/empty
/*
Output: (not output)
*/
Я хочу знать, почему тестовый пример 2 возвратил первую строку, а тестовый пример 3 не прошел?
Мне нужно получить одно изображение отдельно для каждого запроса на основе идентификатора пригорода.
(идентификатор деда)
Рассмотрим псевдокод ниже:
1. if image ID is equal to 1, return the first row of ImageURL.
2. if image ID is equal to 2, return the second row of ImageURL.
3. if image ID is equal to 3, return the third row of ImageURL.
4. else return the first row.
Я по ошибке забыл присвоить результат переменной $ row в тестовых примерах 2 и 3. Когда я попытался выполнить запросы, он вернул пустой набор результатов.
Наилучшим подходом было использование цикла foreach для извлечения данных из результата и проверки равенства строк.
Вышеуказанный подход реализован в следующем фрагменте кода.
$query = "SELECT i.*, p.property_id, s.suburb_id
FROM property_images i
LEFT JOIN properties p
ON i.property_id = p.property_id
LEFT JOIN suburbs s
ON p.suburb_id = s.suburb_id
WHERE s.suburb_id = 60
ORDER BY p.property_id";
$result = $conn->query($query);
$images = array();
foreach($result as $row){
extract($row);
//$images[] = $image_location . '<br />';
if($property_image_id == 1){
print_r($image_location);
}else if($property_image_id == 2){
print_r($image_location);
}else if($property_image_id == 3){
print_r($image_location);
}
}