您好我正在写一个简单的博客,我想从使用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 docs我找到了这个连接示例,但我无法弄清楚它是如何工作的。我只想使用用户ID从users表中获取用户名。
用户表:id, username, e-mail, password, name
帖子表:id, public, title, body, creator_id
答案 0 :(得分: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;
}
答案 1 :(得分:0)
根据您的数据库查看 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();
}
答案 2 :(得分:0)
根据您的表格用户,列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();
}