【问题标题】:Codeigniter joinsCodeigniter 加入
【发布时间】:2014-12-08 12:35:15
【问题描述】:

你好,我正在写一个简单的博客,我想从使用 codeigniter 的活动记录写这篇文章的人那里获取用户名。

到目前为止我有这个模型:

function get_posts($num = 20, $start = 0)
{
    $this->db
         ->select('*')
         ->from('blog')
         ->join('users', 'users.user_id = blog.creator_id')
         ->where('public', TRUE)
         ->order_by('post_id', 'DESC')
         ->limit($num, $start);
    $query = $this->db->get();
    return $query->result_array();
}

从 codeigniter 文档中我找到了这个连接示例,但我无法弄清楚它是如何工作的。我只想使用用户 ID 从用户表中获取用户名。

数据库

用户表:id, username, e-mail, password, name

帖子表:id, public, title, body, creator_id

【问题讨论】:

  • 不知何故我没有得到任何错误。但是我没有得到我想要的。这是我第一次使用联接。

标签: php mysql codeigniter


【解决方案1】:

您只能在选择字段中使用username

另外,获取数组中的所有usernames

function get_posts($num = 20, $start = 0)
{
    $this->db
         ->select('users.username')
         ->from('blog')
         ->join('users', 'users.user_id = blog.creator_id')
         ->where('public', TRUE)
         ->order_by('post_id', 'DESC')
         ->limit($num, $start);
    $query = $this->db->get();
    $usernames = array();
    foreach ($query->result_array() as $curr) {
      $usernames[] = $curr['username'];
    }
    $usernames = array_unique($usernames);
    return $usernames;
}

【讨论】:

    【解决方案2】:

    查看 users.user_id 必须是 users.id 根据您的数据库

    function get_posts($num = 20, $start = 0)
    {
    $this->db
         ->select('*')
         ->from('blog')
         ->join('users', 'users.id = blog.creator_id')
         ->where('public', TRUE)
         ->order_by('post_id', 'DESC')
         ->limit($num, $start);
    $query = $this->db->get();
    return $query->result_array();
    }
    

    【讨论】:

    • 你好,这仅返回 '1' 即 id。我怎样才能得到这个名字?
    • 确保表 "blog""posts"
    • 在查询中返回 ->from('blog') 并且您在第二个表中使用 2 个表定义的数据库是 posts
    【解决方案3】:

    根据您的表用户,coulmn user_id 不存在,您只有 id 所以将您的代码从users.user_id 更改为user.id

    function get_posts($num = 20, $start = 0)
    {
        $this->db
             ->select('*')
             ->from('blog')
             ->join('users', 'users.id = blog.creator_id')
             ->where('public', TRUE)
             ->order_by('post_id', 'DESC')
             ->limit($num, $start);
        $query = $this->db->get();
        return $query->result_array();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 2013-03-11
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多