【问题标题】:Codeigniter populate nested associationsCodeigniter 填充嵌套关联
【发布时间】:2015-05-23 02:30:14
【问题描述】:

这是我需要的数据库结果

{comment: 'hello there', user: [{name: 'sahan', id: 1}], id: 2}

用于获取 cmets 的函数

public function get_comments(){
    $query = $this->db->get('comments');
    return $query->result_array();
}

我有一个 cmets 表和一个 users 表,当用户 cmets 在某事上时

comment is saved as follows
comment > Comment text
user: userid

因此,当显示数据时,我需要 codeigniter 使用从用户表中找到的用户数据填充用户字段

有人知道怎么做吗? 我在 SailsJS 中使用了此功能,但不知道如何在 CodeIG 中执行此操作 Sails.js populate nested associations

【问题讨论】:

  • 我们能看到您用来从数据库中提取 cmets 的代码吗?
  • 有什么想法@nivixzixer好吗?
  • 只是好奇,但你为什么要将用户数据放在一个数组中?每个评论只有一个用户,对吧?
  • 这样我就可以轻松呈现我的观点,你知道谁发表了评论等等

标签: sql codeigniter sails.js


【解决方案1】:

Codeigniter 的活动记录不如 SailJS 活动记录先进,但您可以在同一方法中通过两个查询来实现您的要求。

我假设comments 表通过user_id 字段具有users 表的外键。

public function get_comments() {

    /* Get all the comments */
    $query = $this->db->get('comments');
    $comments = $query->result_array();

    /* Loop through each comment, pulling the associated user from the db */
    foreach $comments as &$comment {
        $query = $this->db->get_where('users', array('id' => $comment['user_id']));
        $user = $query->result_array();

        /* Put the user's data in a key called 'user' within the  comment array */
        $comment['user'] = $user;

        /* Remove the unnecessary user_id and $user variable */
        unset($comment['user_id']);
        unset($user);
    }
    return $comments;
}

【讨论】:

  • 如果我执行 SQL Join 会怎样?喜欢这里的这个例子吗? tutorialspoint.com/sql/sql-using-joins.htm
  • 可以,但是将用户信息存储在数组中会变得很复杂。
  • 那么您认为您的解决方案是否更有效率?
  • 也许效率不高,但更简单。如果您愿意,可以使用原始 SQL 和连接来提高效率。
  • 那么就像我添加的链接一样吗?这就是你的意思原始sql?
猜你喜欢
  • 2014-06-20
  • 2014-12-19
  • 2012-04-23
  • 2017-08-11
  • 2015-12-06
  • 2018-01-20
  • 2013-03-16
  • 2014-06-12
相关资源
最近更新 更多