草庐IT

php - 从 CodeIgniter(或任何 MVC 平台)的数据库中提取数据?

coder 2023-10-12 原文

我在模型中有这个:

public function index_loop() { 
        $post_user = $this->db->query("SELECT posts.post_title, posts.post_content, posts.post_date, users.username FROM posts LEFT JOIN users ON posts.user_id = users.user_id ORDER BY posts.post_ID DESC");
        //$categories = $this->db->query("SELECT categories.cat_name, categories.cat_id FROM  
        //$comments = $this->db->query("SELECT COUNT(comment_id) FROM comments WHERE
        return $post_user->result_array();
    }

我需要的是显示每个帖子和评论的类别(尽管我猜想如果我弄清楚类别通过与评论的方式相同)

在查看文件中:

 <?php foreach($posts as $zz) { ?>
         <div class="article">
           <h2><?php echo $zz['post_title']; ?></h2>
           <p>Posted by <a href=""><?php echo $zz['username']; ?></a> | Filed under <a href="#">templates</a>, <a href=>internet</a></p>
            <p><?php echo $zz['post_content']; ?></p>
           <p><a href=>Read more</a> | <a href=>Comments (5)</a> | <?php echo $zz['post_date']; ?></p>
        </div> <?php } ?>

因此,如果我想在每个博客上循环分类,我需要该博客 ID,如果我从模型进行所有查询,我该如何获取它? 评论也一样

我做一个复杂的大数据库查询(这很难但我能做到)好还是我可以做 2 或 3 个单独的小查询好?

最佳答案

Codeigniter 允许您将数据库结果作为对象(例如模型对象)返回,这使得数据更易于使用。您可以向 Posts 表发出初始查询,在您的结果集中包含 posts.id 字段,并传递您的 Post_model 的名称$db->query->result() 函数告诉 codeigniter 你希望你的结果作为 Post_model 类的实例返回。

然后,您可以将 Post_model 类的方法定义为 post_idGetCategoriesGetComments post_id,然后调用这些方法来填充从查询返回的每个 Post_model$categories$comments 集合。

举个例子,希望对你有帮助

    public class Post_model extends CI_Model
    {

        // All the properties in the Posts table, as well as a couple variables to hold the categories and comments for this Post:
        public $id;
        public $post_title;
        public $post_content;
        public $post_date;
        public $username;        
        public $categories;
        public $comments;

        public function index_loop() 
        { 
                return $this->GetAllPosts();
        }

        // function to get all posts from the database, including comments and categories.
        // returns an array of Post_model objects
        public function GetAllPosts()
        {
                // define an empty array to hold the results of you query.
                $all_posts = array();

                // define your sql query. NOTE the POSTS.ID field has been added to the field list
                $sql = "SELECT posts.id, 
                               posts.post_title, 
                               posts.post_content, 
                               posts.post_date,
                               users.username
                        FROM posts LEFT JOIN users ON posts.user_id = users.user_id
                        ORDER BY posts.post_id DESC";

                // issue the query
                $query = $this->db->query($sql);

                // loop through the query results, passing a string to result() which represents a class to instantiate 
                //for each result object (note: this class must be loaded)

                foreach($query->result("Post_model") as $post)
                {
                        $post->categories = $this->GetPostCategories($post->id);
                        $post->comments = $this->GetPostComments($post->id);
                        $all_posts[] = $post;
                }

                return $all_posts;
        }

        // function to return categories for a given post_id.
        // returns an array of Category_model objects.
        public function GetPostCategories($post_id)
        {
                $sql = "SELECT category.id, ... WHERE post_id = ?";
                $query = $this->db->query($sql, array($post_id));
                $categories = array();
                foreach($query->result("Category_model") as $category)
                {
                        $categories[] = $category;
                }
                return $categories;
        }

        // function to return comments for a given post_id. 
        //returns an array of Comment_model objects
        public function GetPostComments($post_id)
        {
                $sql = "SELECT comment.id, ... WHERE post_id = ?";
                $query = $this->db->query($sql, array($post_id));
                $comments = array();
                foreach($query->result("Comment_model") as $comment)
                {
                        $comments[] = $comment;
                }
                return $comments;
        }    
}

然后,在您看来,您可以将 $posts 数组作为 Post_model 对象而不是 result_arrays 进行访问:

<?php foreach($posts as $zz) { ?>
         <div class="article">
           <h2><?php echo $zz->post_title; ?></h2>
           <p>Posted by <a href=""><?php echo $zz->username; ?></a> | 

              Filed under 
               <?php foreach($zz->categories as $category) {
                        echo '<a href="#">{$category->name}</a>, ';
                     }
               ?>
           </p>
           <p><?php echo $zz->post_content; ?></p>
           <p><a href=>Read more</a> | <a href=>Comments (5)</a> | <?php echo $zz->post_date; ?></p>
        </div> <?php } ?>

至于效率问题,这取决于很多因素(数据库是否与网络服务器位于同一台机器上?有多少帖子?等)。单个大型查询通常会比几个较小的查询执行得更快,但它需要进行分析才能真正确定性能提升是否值得寻求。我总是更喜欢尝试编写可读/可理解的代码,而不是以增加复杂性为代价进行优化。

关于php - 从 CodeIgniter(或任何 MVC 平台)的数据库中提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153419/

有关php - 从 CodeIgniter(或任何 MVC 平台)的数据库中提取数据?的更多相关文章

  1. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  4. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  5. ruby-on-rails - RSpec:避免使用允许接收的任何实例 - 2

    我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_

  6. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  7. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  8. FOHEART H1数据手套驱动Optitrack光学动捕双手运动(Unity3D) - 2

    本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01  客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02  数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit

  9. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

  10. ruby-on-rails - 创建 ruby​​ 数据库时惰性符号绑定(bind)失败 - 2

    我正在尝试在Rails上安装ruby​​,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf

随机推荐