2017-06-21 135 views
0

我正在使用Codeigniter,我想要做的是返回连接表(item_gallery)gallery_id是最低值的查询。而主要查询按项目desc排序post_datecodeigniter活动记录group_by返回加入表记录的随机排序编号

以下代码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 | 

回答

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(); 
} 
0

更换

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

随着

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

我想 “item_gallery.id” 最低值,而items.post_date DESC –

+0

然后用'item_gallery.id'取代'items.post_date' –

+0

$这个 - > DB-> GROUP_BY( “item_gallery.item_id”);应该选择联接表item_gallery.id的较低值。 while $ this-> db-> order_by('items.post_date','Desc'); –