【发布时间】:2021-07-24 08:06:08
【问题描述】:
我有一张食物表,我将类别 ID 存储为逗号分隔,如下图所示 food table
我在模型中创建了一个方法,它以数组(类别 ID)作为参数,并从参数中获取 ID 与数组匹配的食物。
我做了以下查询
if(count($categoryIds) > 0 && count($allergyIds) == 0 ){
$tempArr = array();
foreach($categoryIds as $eachCategoryId){
$sql = "Select food.food_id,food_name,food_image,food_thumbnail,description,food_variations.price as price,is_active
from food
join food_variations on food_variations.food_id = food.food_id
where FIND_IN_SET($eachCategoryId,category_id)
and food.restaurant_id = $restaurantId
and food.is_active = 1
and food.is_deleted = 0
and food.food_status = 3
and food_variations.food_variation_id = food.default_food_variation_id";
$result = $this->db->query($sql)->result_array();
array_push($tempArr, $result);
}
echo "<pre>";print_r($tempArr);
}
下面是上面查询的结果
Array
(
[0] => Array
(
[0] => Array
(
[food_id] => 10
[food_name] => Rama Mckee
[food_image] =>
[food_thumbnail] =>
[description] => asdfs
[price] => 34
[is_active] => 1
)
[1] => Array
(
[food_id] => 6
[food_name] => Rishi
[food_image] =>
[food_thumbnail] =>
[description] => test
[price] => 120
[is_active] => 1
)
[2] => Array
(
[food_id] => 5
[food_name] => test
[food_image] => http://localhost/gastroapp/assets/uploads/food_images/a5918726b920e7cbfc7f90e1afc48091.jpg
[food_thumbnail] => http://localhost/gastroapp/assets/uploads/food_images/thumb/a5918726b920e7cbfc7f90e1afc48091.jpg
[description] => test
[price] => 120
[is_active] => 1
)
)
[1] => Array
(
[0] => Array
(
[food_id] => 10
[food_name] => Rama Mckee
[food_image] =>
[food_thumbnail] =>
[description] => asdfs
[price] => 34
[is_active] => 1
)
[1] => Array
(
[food_id] => 7
[food_name] => ezhva
[food_image] =>
[food_thumbnail] =>
[description] => ddsfsd
[price] => 20
[is_active] => 1
)
[2] => Array
(
[food_id] => 8
[food_name] => test
[food_image] =>
[food_thumbnail] =>
[description] => test
[price] => 22
[is_active] => 1
)
[3] => Array
(
[food_id] => 6
[food_name] => Rishi
[food_image] =>
[food_thumbnail] =>
[description] => test
[price] => 120
[is_active] => 1
)
)
)
我得到了重复的结果,我认为这也可能导致性能问题。
以下是当我每种食物只有一个类别时的查询,这给了我想要的结果。
return $this->db->select('food.food_id,food_name,food_image,food_thumbnail,description,food_variations.price as price,is_active')
->from('food')
->join('food_variations', 'food_variations.food_id = food.food_id')
->where_in('category_id',$categoryIds)
->where('food.restaurant_id', $restaurantId)
->where('food.is_active', '1')
->where('food.is_deleted', '0')
->where('food.food_status','3')
->where('food_variations.food_variation_id IN( select food_variation_id from food_variations where food_variation_id = food.default_food_variation_id )')
->get()
->result_array();
请帮忙。
【问题讨论】:
-
对于mysql,建议使用字符串列来保存静态数据,而不是只添加ID。您必须存储具有相关值的对象,而不仅仅是整数。如果你想要它的关系数据,最好使用中间表。
-
我已经更新了我的问题。请立即查看。
标签: php mysql sql codeigniter