Codeigniter中的查询表和相关表

时间:2014-08-11 14:29:01

标签: php sql codeigniter

我在数据库中设置了两个表,一个"帖子"表和"图像"表。 Images表中的行与Posts表的ID相关,因此任何时候都可以有一个Post,但分配给它的Image表中有多行。我不想运行联接,因为当它将帖子添加到图像中的每一行时,它会导致帖子表中的重复内容

我希望能够以下列方式迭代这些内容:

foreach(posts as post)
{
    foreach(post['image'] as image)
    {
        // something here
    } 
}

在Django中,可以通过以下方式在我的模型中设置:

class Posts

    # something here

   def get_images(self):
       return self.images_set.select_related('post')

是否可以使用Active Record在Codeigniter模型中进行类似的设置?我能够做到的唯一方法是查询Posts表,循环结果并在循环内查询Images表。然后将所有内容设置为新阵列并将其发送到控制器。但这看起来并不高效。这是一个例子:

public function get_posts()
{
    // Grab all posts
    $query = $this->db->get('posts_table');
    $results = $query->result_array();

    // Arrays for storage
    $photoArray = array();
    $postsArray = array();
    $postsResultArray = array();

    $postsResultArray[] = $results;

    // Query photos in DB
    foreach($photoResultArray[0] as $row)
    {
        $query = $this->db->get_where('uploads', array('tableName' => 'posts_table', 'recordNum' => $row['num'], 'fieldname' => 'images'));
        $results = $query->result_array();

        foreach($results as $row)
        {
            $photoArray[] = $row;
        }

    }

    // Associate each post with photo if available
    foreach($postsResultArray[0] as $post)
    {
        foreach($photoArray as $row)
        {
            if($row['recordNum'] == $post['num']) 
            {
                $post['image'] = $row['urlPath'];
            }
        }
        $postsArray[] = $post;
    }

    return $postArray;
}

1 个答案:

答案 0 :(得分:0)

试试这个

 public function get_posts()
 {
     // Grab all posts
     $query = $this->db->get('images');
     $results = $query->result_array();

     // Arrays for storage
     $photoArray = array();
     $postsArray = array();

     $photoResultArray[] = $results;

     // Query photos in DB
     foreach($photoResultArray as $row)
     {
         $photoArray[$row->id] = $row->image;
     }

     $query2 = $this->db->get('posts');
     $results2 = $query2->result_array();
     $postsResultArray[] = $results2;

     // Associate each post with photo if available
     foreach($postsResultArray[0] as $post)
     {
         $postsArray[] = $photoArray[$post->image_id];
     }

     return $postArray;
 }