codeigniter活动记录group_by返回连接表记录id的随机排序

时间:2017-06-21 06:57:27

标签: codeigniter activerecord codeigniter-3

我使用Codeigniter,我想要做的是返回连接表(item_gallery)的查询gallery_id是最低值。而主要查询按项目post_date的desc命令

以下代码group_by选择item_gallery gallery_id的随机值。但我想要item_gallery gallery_id的最低值。

  public function shopItems($id) {

    $this->db->select("*");
    $this->db->from('items');
    $this->db->join('item_gallery', 'items.id = item_gallery.item_id', 'left');
    $this->db->where('items.user_id', $id);     
    $this->db->order_by('items.post_date', 'Desc');
    $this->db->group_by("item_gallery.item_id");
    $query = $this->db->get();
    return $query->result();
}

数据库结构

项目表

|    id    |  slug  |  user_id  |  post_date |

|    12    |  test  |    111    |  12/5/2017 |

项目图库

| gallery_id |  item_id  |     image     | 

|     121    |    12     |  profile.png  |   -- i want this record selected
|     122    |    12     |  gallery.png  | 

2 个答案:

答案 0 :(得分:0)

替换

$this->db->order_by('items.post_date', 'Desc');

使用

 $this->db->order_by('items.id', 'Desc');

答案 1 :(得分:0)

public function shopItems($id, $limit, $start) {

date_default_timezone_set('Asia/Colombo');
$expire = date('Y-m-d');
$this->db->select("*,(SELECT image FROM item_gallery WHERE item_id = 
items.id ORDER BY gallery_id ASC LIMIT 1) AS profile_img");
$this->db->from('items');
$this->db->join('item_gallery', 'items.id = item_gallery.item_id', 'left');
$this->db->where('items.exp_date >', $expire);
$this->db->group_start();
$this->db->where("items.status = 'yes'");
$this->db->or_where("items.status = 'edit'");
$this->db->group_end();
$this->db->where('items.user_id', $id);
$this->db->limit($limit, $start);
$this->db->order_by('items.post_date', 'Desc');
$this->db->group_by("item_gallery.item_id");
$query = $this->db->get();
return $query->result();
}