我有两个mysql表order
和orderitems
现在我想在一个单独的监视器上使用angularjs显示这些数据
我的桌子结构:
表格order
包含id, table_id, date_time
表格orderitems
包含order_id, food_item, item_qty, dalivery
现在我想在单独的html div中显示这些数据。 table_id
为标题,orderitems
为内容。
为此,我想要一个像这样的数据结构
[{
table_id,
date_time,
items: [
{
food_item,
item_qty,
delivery
},
{
food_item,
item_qty,
delivery
}
]
}]
那么如何使用codeigniter或MySQL进行查询呢?
答案 0 :(得分:1)
您可以选择包含订单数据的所有订单商品
这是一个Mysqli解决方案
$mysqli = new mysqli("example.com", "user", "password", "database");
$query = " SELECT * FROM order LEFT JOIN orderitems ON order.id = orderitems.order_id ";
$stmt = $mysqli->prepare($query);
!$stmt ? die('error') : "";
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
if($lastOrderId != $row['id']){
if($order){
$finalArray[] = $order;
}
$lastOrderId = $row['id'];
$order = new \stdClass();
//$order->id = $row['id'];
$order->table_id = $row['table_id'];
$order->date_time = $row['date_time'];
$order->items = [];
}
if($row['food_item']){
$orderItem = new \stdClass();
$orderItem->food_item = $row['food_item'];
$orderItem->item_qty = $row['item_qty'];
$orderItem->dalivery = $row['dalivery'];
$order->items[] = $orderItem;
}
}
//last order in loop
if($order){
$finalArray[] = $order;
}
print_r($finalArray) ;
exit;
尝试现场演示(https://eval.in/835997)
此演示依赖于虚假数据进行测试
$row1 = ["id"=>1,"table_id"=>5,"date_time"=>"2017-12-31","food_item"=>1,"item_qty"=>1,"dalivery"=>"yes"];
$row2 = ["id"=>1,"table_id"=>5,"date_time"=>"2017-12-31","food_item"=>2,"item_qty"=>2,"dalivery"=>"no"];
$row3 = ["id"=>2,"table_id"=>5,"date_time"=>"2017-12-31","food_item"=>3,"item_qty"=>3,"dalivery"=>"yes"];
$row4 = ["id"=>2,"table_id"=>5,"date_time"=>"2017-12-31","food_item"=>4,"item_qty"=>4,"dalivery"=>"no"];
$rows = [$row1, $row2, $row3, $row4];
此输出
Array
(
[0] => stdClass Object
(
[table_id] => 5
[date_time] => 2017-12-31
[items] => Array
(
[0] => stdClass Object
(
[food_item] => 1
[item_qty] => 1
[dalivery] => yes
)
[1] => stdClass Object
(
[food_item] => 2
[item_qty] => 2
[dalivery] => no
)
)
)
[1] => stdClass Object
(
[table_id] => 5
[date_time] => 2017-12-31
[items] => Array
(
[0] => stdClass Object
(
[food_item] => 3
[item_qty] => 3
[dalivery] => yes
)
[1] => stdClass Object
(
[food_item] => 4
[item_qty] => 4
[dalivery] => no
)
)
)
)
答案 1 :(得分:0)
使用Codeigniter
。对于PDO可能相同。
$data = array();
$tables = $this->db->select('table_data.*, order.id As order_id, order.date_time')
->join('order', 'order.table_id = table_data.id')
->where('order.status', 'Pending')
->get('table_data')->result_array();
foreach ($tables as $table) {
$items = $this->db->select('orderitems.food_item, orderitems.item_qty')
->where('order_id', $table['order_id'])
->get('orderitems')->result_array();
array_push($data, array('details' => $table, 'items' => $items));
}
$this->response($data);