0

CodeIgniter 和 MVC/OOP 也是新手。我目前正在尝试解决的问题涉及 2 张桌子。


画廊表

ID

姓名

客户ID


客户表

ID

姓名


图库['clientID'] 引用了客户端['id'],因此我可以检索名称。目前我的 gallery_model.php 文件看起来像

class Gallery_model extends CI_Model
    {

        public function __construct()
        {
            $this->load->database();
        }

    //Get all in progress galleries from client
    public function get_progress($id = FALSE , $clientRef = '205')
    {
        if($id == FALSE) {
            $query = $this->db->get_where('gallery', array('clientRef' => $clientRef, 'finish' => '0' ));
            return $query->result_array();
        }
    }
    //Get all proofed galleries from client
    public function get_proofed($id = FALSE , $clientRef = '205')
    {
        //get all galleries from client
        if ($id == FALSE) {
            $query = $this->db->get_where('gallery',array('clientRef' => $clientRef, 'finish' => '1'));
            return $query->result_array();
        }
    }

    //get the gallery selected
    public function get_gallery($id , $clientRef = '205')
    {
        //This returns individual galleries
        $query = $this->db->get_where('gallery', array('id' => $id));
        return $query->row_array();
    }
}

我的控制器看起来像:

    public function index()
    {
        //Proofed Albums
        $data['gallery'] = $this->gallery_model->get_proofed();
        //Albums that are in progress
        $data['in_progress'] = $this->gallery_model->get_progress();

        $this->load->view('templates/header',$data);
        $this->load->view('gallery/index',$data);
        $this->load->view('templates/footer');
    }

然后视图的输出是

$gallery['name'] - $gallery['clientId']

像这样的最佳实践是什么。我知道这可能很简单,但我想开始正确地做这件事。我应该使用$this->db->join();

在此先感谢您的帮助。

4

2 回答 2

2

跟进威廉的回答,您可以使用 CI 的 Active Record 进行加入

$this->db->from('gallery')->join('client', 'gallery.id = client.id')->get()
于 2012-11-24T01:24:10.807 回答
1

使用$this->db->join()确实是在一个查询中从多个表中获取信息的最佳方式(也是通过 Active Records 完成而不添加您自己的 SQL 的唯一方式)。

您可能已经意识到这一点,但为了以防万一(并且为了将来访问此页面的人的利益),CodeIgniter 用户指南有一个很好的页面详细说明了如何使用 Active Records。

Inner Join 的默认值应该适合您的目的。如果您有没有客户链接的图库条目,并且您希望它们包含在结果中,那么您可能需要考虑其他类型的连接,您可以在此处阅读

于 2012-11-24T01:20:26.907 回答