首先上传图库图片为个人资料图片

时间:2017-06-22 07:55:00

标签: mysql codeigniter activerecord codeigniter-3

我正在使用Codeigniter,我想要做的是当用户上传图片到图库时,首先上传的图片应该被选为个人资料图片。

我的数据库结构

项目表

|    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  | 

我使用此代码从图库表中选择随机图片。

    public function shopItems($id) {

    $this->db->select("*,MIN(item_gallery.gallery_id)");
    $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();
}

3 个答案:

答案 0 :(得分:0)

通过添加和附加自动增量列来更改item_gallery表结构。

| gallery_id |  item_id  |     image     | 

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

现在尝试以下代码段:

public function shopItems($id)
{

    $this->db->select('id');
    $this->db->from('items');
    $this->db->where('user_id', $id);
    $query = $this->db->get();
    $item_id = $query->row('id');

    $this->db->select("*,(SELECT image FROM item_gallery WHERE item_id = '$item_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.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();
}

现在shopItems会返回用户上传的第一张图片。

答案 1 :(得分:0)

只需编写像这样的查询

public function shopItems($id) {
    $sql = "Select * from items a left join (Select item_id, image from items_galary group by item_id limit 1) b on a.id = b.item_id and a.id = '$id'";
    $query = $this->db->query($sql);
    return $query->result_array();
}

试试这个

答案 2 :(得分: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();
}