代码点火器加入


Codeigniter joins

你好,我正在写一个简单的博客,我想从使用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();
}

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

数据库

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

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

您只能在选择字段中获取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;
}
看看

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();
}

根据你的表用户,可能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();
}