0

我有一个在 codeigniter 中开发的网站,我想在其中检索特定 tee 的评论。我有一个像这样的 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
  }
}

我尝试过加入:-左-右-左外-右外

但是并没有解决问题,有没有办法做到这一点?谢谢

4

3 回答 3

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.

下面是我喜欢在通话后使用的一个方便的小片段。它使 rowObjectArray's 代替。

$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) : ""; } }
于 2013-06-25T17:10:22.950 回答
0

用于$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');
于 2013-06-25T16:09:00.640 回答
0

选项一:

for ($i = 0; $i < count($records); $i++)
{
 $data = $records[$i];
 // work with date.
 if($i == 1)
   break;
}

选项二:只需将第一行分配给 var。

$row = $records['tee']['comment'][0];
于 2013-06-25T16:20:42.330 回答