[英]Retrieve only one row of comment
我在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,因为在该tee中有两个注释。
我的目标是仅检索其中包含注释数组的一行:
tee{
id,
name,
created,
modified
comment{
[0]
id,
tee_id,
comment,
created,
modified
[1]
id,
tee_id,
comment,
created,
modified
}
}
我已尝试加入连接:-左-右-左外部-右外部
但是不能解决问题,有办法吗? 谢谢
我爱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) : ""; } }
使用$this->db->limit(1)
检索单个记录。
根据对此问题的公认答案,您可能需要在选择之前添加限制声明:
$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');
选项一:
for ($i = 0; $i < count($records); $i++)
{
$data = $records[$i];
// work with date.
if($i == 1)
break;
}
选项二:只将第一行分配给var。
$row = $records['tee']['comment'][0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.