Jus*_*inB 2 sql join codeigniter
我有两张桌子A和B,B和A有很多:1关系.
当从A查询行时,我也希望将相应的B记录作为数组返回并从A添加到结果数组中,所以我最终得到如下内容:
A-ROW
   field
   field
   B-ITEMS
      item1
      item2
      item3
是否有一种干净的方法可以使用一个查询(可能是一个连接?),或者我应该只对A的id执行第二次B查询并将其添加到结果数组中?
将表B连接到表A上会更有效.它不会为您提供所需形状的数据.但是您可以迭代此结果并将数据构建为所需的形状.
这里有一些代码来说明这个想法:
// Join table B on table A through a foreign key
$sql = 'select a.id, a.x, b.y
    from a
    left join b on b.a_id=a.id
    order by a.id';
// Execute query
$result = $this->db->query($sql)->result_array();
// Initialise desired result
$shaped_result = array();
// Loop through the SQL result creating the data in your desired shape
foreach ($result as $row)
{
    // The primary key of A
    $id = $row['id'];
    // Add a new result row for A if we have not come across this key before
    if (!array_key_exists($id, $shaped_result))
    {
        $shaped_result[$id] = array('id' => $id, 'x' => $row['x'], 'b_items' => array());
    }
    if ($row['y'] != null)
    {
        // Push B item onto sub array
        $shaped_result[$id]['b_items'][] = $row['y'];
    }
}