我正在尝试创建一个目录,但在结果中调用“列表图像”时遇到问题。问题是只有某些列表会有图像,否则如果没有,我希望他们使用我设置的默认图像。当我尝试将“图像”表添加到查询中时,它仅返回具有可用图像的结果(忽略其他没有图像的列表)。
这是我的代码:
public function search($neighborhood = null, $biz_filter = null) {
$neighborhood = $this->uri->segment(3);
$biz_filter = $this->uri->segment(4);
// SELECT
$this->db->select('*');
// MAIN TABLE TO GRAB DATA
$this->db->from('biz');
// TABLES TO JOIN
$this->db->join('city', 'city.city_id = biz.biz_cityID');
$this->db->join('zip', 'zip.zip_id = biz.biz_zipID', 'zip.zip_cityID = city.city_id');
$this->db->join('state', 'state.state_id = city.city_stateID');
$this->db->join('neighborhood', 'neighborhood.neighborhood_id = biz.biz_neighborhoodID');
$this->db->join('biz_filter', 'biz_filter.bizfilter_bizID = biz.biz_id');
$this->db->join('biz_category', 'biz_category.bizcategory_id = biz_filter.bizfilter_bizcategoryID');
if ($neighborhood != "-" AND $biz_filter != "-") {
$this->db->where('biz_category.bizcategory_slug', $biz_filter);
$this->db->where('neighborhood.neighborhood_slug', $neighborhood);
} elseif ($neighborhood != "-" AND $biz_filter == "-") {
$this->db->where('neighborhood.neighborhood_slug', $neighborhood);
} elseif ($neighborhood == "-" AND $biz_filter != "-") {
$this->db->where('biz_category.bizcategory_slug', $biz_filter);
} else {
}
// ORDER OF THE RESULTS
$this->db->group_by('biz_name asc');
// RUN QUERY
$query = $this->db->get();
// IF MORE THAN 0 ROWS ELSE DISPLAY 404 ERROR PAGE
return $query;
}
如何在单独的表中添加包含 Logo 图像的“图像”(“image.image_file”)。 “image”表和“biz”表通过我在每个表中传递的企业 ID 连接(image.biz_id = biz.biz_id)。
有人知道如何解决查询才能正常工作吗?
最佳答案
只需使用
$this->db->join('image', 'image.biz_id = biz.biz_id', 'left');
左加入您的图像
表。当表中没有 biz_id 的记录时,image.image_file
将具有空值。阅读 here了解更多信息。
您可以使用 COALESCE函数用预定义的默认值替换“空”图像。只需将您的行替换为 $this->db->select('*');
即可:
// SELECT
$this->db->select("*, COALESCE(image.image_file, 'images/not_found.png') as my_image_file");
渲染输出时,请确保使用 my_image_file
列作为图像。
旁注:避免在选择中使用“*”。仅选择您实际需要的列。选择所有列会不必要地增加数据库服务器资源的负载。
关于MySQL 并仅使用一些结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987943/