我有一个在codeigniter中开发的网站,我想要检索特定T恤的评论。 我有一个像这样的桌子:
- id
- user_id
- name
- created
- modified
表tee_comments就是这样:
- id
- user_id
- tee_id
- created
- modified
我已完成此查询:
$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified');
$this->db->from('tee');
$this->db->join('tee_comments', 'tee_comments.tee_id = tee.id','left outer');
$this->db->order_by("tee.created", "desc");
$query = $this->db->get();
通过这个查询,我检索了两排三通,因为我在那个发球台上有两条评论。
我的目标是只检索一行内部有一系列评论,如:
tee{
id,
name,
created,
modified
comment{
[0]
id,
tee_id,
comment,
created,
modified
[1]
id,
tee_id,
comment,
created,
modified
}
}
我尝试过加入: - 剩下 - 对 - 左外 - 右外
但是没有解决问题,有没有办法做到这一点? 感谢
答案 0 :(得分:1)
我喜欢CodeIgniter!我经常使用它!这里有2个非常简单的选项:
一种方法是使用limit
。
$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified');
$this->db->join('tee_comments', 'tee_comments.tee_id = tee.id','left outer');
$this->db->order_by("tee.created", "desc");
$query = $this->db->limit(1)->get('tee');
另一种方法是获取results Array
$query = $this->db->get();
$results = $query->result(); // gets return as an array
$row = $results[0]; // will be first row in results array
请记住,$row
将以object(stdClass)
的形式返回,这意味着您必须像$row->column_name
一样从中检索内容。
我打算在电话会议后使用一个方便的小片段。它会使行Object
成为Array
。
$results = $db->get('tee')->result(); // snippet comes after you have result array
// snippet here
foreach ($r as $k => $v) { $results[$k] = array(); foreach ($v as $kk => $vv) { $results[$k][$kk] = $vv != "NULL" ? trim($vv) : ""; } }
答案 1 :(得分:0)
使用$this->db->limit(1)
检索单个记录。
根据this question上接受的答案,您可能需要将限制声明放在选择之前:
$this->db->limit(1);
$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified');
$this->db->from('tee');
答案 2 :(得分:0)
选项一:
for ($i = 0; $i < count($records); $i++)
{
$data = $records[$i];
// work with date.
if($i == 1)
break;
}
选项二: 只需将第一行分配给var。
$row = $records['tee']['comment'][0];