Как отфильтровать данные в БД с помощью Codeigniter?

У меня есть две таблицы — изображения и категории, которые выглядят так:

    CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `images` (
`id` int(11) NOT NULL,
`categories_id` int(11) NOT NULL,
`file` text NOT NULL,
`caption` text NOT NULL,
`description` text NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

У меня есть 4 категории, и мне нужно фильтровать и отдельно показывать изображения каждой категории

Я пытаюсь, как это, но он отображает все изображения

**Model:**
public function org_filter()//filter categories
{
$this->db->select('i.file,i.categories_id,c.id,c.title',false);
$this->db->from('images as i');
$this->db->join('categories as c','i.categories_id = c.id','inner');//join tables based on the foreign key
$this->db->where('c.title','organizers');//set filter
$query = $this->db->get();//get data*/
return $query;
}

**Controller**
$data=array(
'r_images'   => $this->Gallery_model->org_filter(),
);

$this->load->view('layouts/main', $data);

**View**
<h3 class="svgbg">ORGANIZERS</h3><!--name of the first category-->
<?php foreach($r_images->result() as $img) : ?>
<div>
<div class="thumbnail">
<?=img($img->file)?>
</div>
</div>
<?php endforeach; ?>

Поэтому моя цель — сделать динамическую выборку из БД для просмотра.

П.С .: Извините за плохой японский

0

Решение

Вы можете попробовать этот код для вашего решения ..

Category_model.php

добавить эту функцию в cagetory модели

//Model Category
public function get_category(){
$q = "select * from categories";
$rs = $this->db->query($q);
return $rs->result();
}

Gallery_model.php

добавить эту функцию в галлерею модели.

//Gallery_model
public function org_filter($categoryId)//filter categories
{
$q =  "SELECT * FROM images INNER JOIN categories on images.categories_id = categories.id WHERE categories.id =".$categoryId;
$q = $this->db->query($q)->result();
return $q;
}

Gallery.php

следующий код добавить в контроллер галереи.

function index()
{
$category = $this->dashboard_model->get_category();

$data = array();
//Controller
//$category = $this->Category_model->get_category();
foreach ($category as $key => $value) {
$data['category'][$key]['title'] = $value->title;
$data['category'][$key]['r_images'] = $this->dashboard_model->org_filter($value->id);
}
$this->load->view('layouts/main', $data);
}

main.php

следующий код добавить в представление файла main.php

<h3 class="svgbg">ORGANIZERS</h3><!--name of the first category-->
<?php foreach($category as $img) :?>
<div>
<?php echo "Category Name: ".$img['title'];?>  <br>
<?php foreach($img['r_images'] as $imgage) :?>
<div class="thumbnail">
<?=img($imgage->file)?> <br>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>

выше всего кода добавьте вашу модель, контроллер и вид. Вы можете получить идеальный выход.

2

Другие решения

Кажется, вы забыли предложение where, поэтому все изображения возвращаются.

попробуйте изменить функцию org_filter следующим образом:

public function org_filter($categoryId)//filter categories
{
$this->db->select('*');
$this->db->from('images');
$this->db->join('categories','images.categories_id = categories.id','inner');//join tables based on the foreign key
$this->db->where('categories.id',$categoryId);
$this->db->on('images.id',10);//set filter
$query = $this->db->get();//get data
return $query;
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector