【问题标题】:best practice with CRUD system and JOIN queries in CodeIgniterCodeIgniter 中 CRUD 系统和 JOIN 查询的最佳实践
【发布时间】:2014-01-31 18:08:42
【问题描述】:

我正在使用 CodeIgniter 开发我的应用程序,并根据我多年前找到的教程(我忘记了 URL)组装了一个非常基本的 CRUD 系统(实际上只是在我的模型中创建、检索、更新和删除函数)。在开发应用程序时,我意识到我必须调用多个模型的检索函数来获取视图所需的数据(即 get_product、get_category、get_buyer 等)。我知道使用 JOIN 查询最适合从多个表中获取数据,但是在具有 CRUD 模型系统的 CodeIgniter 中,JOIN 查询应该在哪里(控制器,在各自的主模型或单独的模型中)?

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    您应该在模型部分处理查询。 这是在 codeigniter 中使用 Active Records 的示例连接查询。

    $this->db->join();
    
    Permits you to write the JOIN portion of your query:
    
    $this->db->select('*');
    $this->db->from('blogs');
    $this->db->join('comments', 'comments.id = blogs.id');
    
    $query = $this->db->get();
    
    // Produces: 
    // SELECT * FROM blogs
    // JOIN comments ON comments.id = blogs.id
    Multiple function calls can be made if you need several joins in one query.
    

    如果您需要特定类型的 JOIN,您可以通过函数的第三个参数指定它。选项有:左、右、外、内、左外和右外。

    $this->db->join('comments', 'comments.id = blogs.id', 'left');
    
    // Produces: LEFT JOIN comments ON comments.id = blogs.id
    

    【讨论】:

    • 好吧,我熟悉使用 Active Record 执行 JOIN,但我特别想知道当它们跨越各种表(并且每个表都有自己的模型)时将它们放置在哪个模型中。
    • 您可以在任何模型中编写连接查询。如果你想用三个模型中的表编写连接,你可以在三个模型中的任何一个中编写连接查询。
    • 没关系。我只是要修改我的基本检索模型以接受将生成复杂 JOIN 查询的额外参数。谢谢大家
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2010-09-22
    • 2013-05-10
    • 1970-01-01
    相关资源
    最近更新 更多