我是Codeigniter
和PHP
的新手,只是在学习。我搜索过这个但找不到合适的答案。我有一个包含一些数据的表,我们称之为posts
,在此表中,每个帖子都有一个category_id
。我有另一个名为categories
的表,在此表中我有两列:id
和name
。
我想加入两个表格,我得到的结果与posts
相同,另一列名为category_name
,将从categories.name
获取。只是无法弄清楚如何做到这一点。
这是我到目前为止所做的事情:
function getPostsWithByCategoryID($numberOfRows, $start, $categoryId)
{
$this->db->select('*');
$this->db->from('posts')->order_by('id','desc')->limit($numberOfRows, $start);
$this->db->where('category_id', $categoryID);
$this->db->join('categories', 'posts.category_id == categories.id');
$query = $this->db->get();
return $query->result_array();
}
提前致谢。
=============================================== =========================
编辑:
在尝试了Adrian Forsius之后回答:
function getPostsWithByCategoryID($numberOfRows, $start, $categoryId)
{
$this->db->select('*, category.name AS category_name');
$this->db->from('posts')->order_by('id','desc')->limit($numberOfRows, $start);
$this->db->where('category_id', $categoryID);
$this->db->join('categories', 'posts.category_id = categories.id');
$query = $this->db->get();
return $query->result_array();
}
我收到了这个错误:
Error Number: 1054: Unknown column 'category.name' in 'field list'
SELECT *, `category`.`name` AS category_name
FROM (`posts`)
JOIN `categories` ON `posts`.`category_id` = `categories`.`id`
WHERE `category_id` IS NULL
ORDER BY `id` desc
LIMIT 20
====
编辑2:
所以我在代码中发现了一些错误并修复了它们,再次尝试,但我仍然收到错误:(错误是使用$categoryID
代替$categoryId
并选择category.name
代替表categories
的真实姓名是categories.name
Error Number: 1052: Column 'id' in order clause is ambiguous
SELECT *, `categories`.`name` AS category_name
FROM (`posts`)
JOIN `categories` ON `posts`.`category_id` = `categories`.`id`
WHERE `category_id` = '3'
ORDER BY `id` desc
LIMIT 20
答案 0 :(得分:1)
替换
$this->db->select('*');
通过
$this->db->select('posts.*');
$this->db->select('categories.name','category_name');
CI的文档相当不错。
答案 1 :(得分:1)
试试这个我觉得你忘了放置=代替==
function getPostsWithByCategoryID($numberOfRows, $start, $categoryId)
{
$this->db->select('*');
$this->db->from('posts')->order_by('id','desc')->limit($numberOfRows, $start);
$this->db->where('category_id', $categoryID);
$this->db->join('categories', 'posts.category_id = categories.id');
$query = $this->db->get();
return $query->result_array();
}
答案 2 :(得分:1)
这应该可以满足您的需求:
function getPostsWithByCategoryID($numberOfRows, $start, $categoryId)
{
$this->db->select('*, categories.name AS category_name');
$this->db->from('posts')->order_by('posts.id','desc')->limit($numberOfRows, $start);
$this->db->where('category_id', $categoryId);
$this->db->join('categories', 'posts.category_id = categories.id');
$query = $this->db->get();
return $query->result_array();
}