Php 仅检索一行注释
我有一个在codeigniter中开发的站点,我想在这里检索特定tee的评论。 我有一个这样的桌上T恤:Php 仅检索一行注释,php,sql,codeigniter,Php,Sql,Codeigniter,我有一个在codeigniter中开发的站点,我想在这里检索特定tee的评论。 我有一个这样的桌上T恤: - id - user_id - name - created - modified - id - user_id - tee_id - created - modified 表中的tee_注释如下: - id - user_id - name - created - modified - id - user_id - tee_id - created - modified 我已完成
- id
- user_id
- name
- created
- modified
- id
- user_id
- tee_id
- created
- modified
表中的tee_注释如下:
- id
- user_id
- name
- created
- modified
- 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
}
}
我已尝试加入:
-左
-对
-左外
-右外
但这并不能解决问题,有办法吗?
谢谢使用$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;
}
我喜欢CodeIgniter!我经常使用它!这里有两个非常简单的选项: 一种方法是使用
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');
另一种方法是获取
结果数组中的第一项
$query = $this->db->get();
$results = $query->result(); // gets return as an array
$row = $results[0]; // will be first row in results array
请记住,$row
将作为对象(stdClass)
返回,这意味着您必须从中检索内容,如$row->column\u name
下面是我喜欢在通话后使用的一个方便的小片段。它使行对象成为数组
$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) : ""; } }
但我必须用他们的评论检索所有tee,例如,我知道limit只能检索一条记录,但不是这种情况,在这种情况下,可能不可能。请参见此处的答案:数据库查询从表的(组合)中检索行。如果你想要一个嵌套结构,你必须自己在php中生成。你必须用相应的tee记录手动聚合注释数据。你的问题表明你只需要一行注释,但你想要实现的包括多个注释?@jeroen he使用的是CI,它返回一个“嵌套结构”@SpYk3HH我们可能使用不同的嵌套结构定义
;它返回包含信息的行,但这些行不包含OP需要的信息子行(注释…)。