I dont know how to convert this long model function to ignited datatable query. I have done small select functions with ignited datatables.Anybody know???
I have no idea about how to covert it. Is there any functions to do it?
public function fetch_data() {
$this->db->from('jil_requirements');
$this->db->join('jil_users', 'jil_requirements.rqm_userid=jil_users.usr_id', 'left');
$this->db->join('jil_merchants', 'jil_requirements.rqm_createdempid=jil_merchants.mer_id', 'left');
$this->db->where('jil_requirements.rqm_permission!=', '4');
$this->db->order_by("jil_requirements.rqm_id", "desc");
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$this->db->select('count(jil_mrorfq.rfq_requirementid) as total');
$this->db->from('jil_mrorfq');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id=jil_mrorfq.rfq_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query2= $this->db->get()->row_object();
$row->total_count = $query2->total;
$this->db->select('count(jil_quotemjdetail.qud_requirementid) as quotemjtotal');
$this->db->from('jil_quotemjdetail');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id=jil_quotemjdetail.qud_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query3= $this->db->get()->row_object();
$row->quotemj_total = $query3->quotemjtotal;
$this->db->select('count(jil_quotejcdetail.qud_requirementid) as quotejctotal');
$this->db->from('jil_quotejcdetail');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id= jil_quotejcdetail.qud_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query4= $this->db->get()->row_object();
$row->quotejc_total = $query4->quotejctotal;
$this->db->select('count( jil_pocjdetail.pocd_requirementid) as pocjtotal');
$this->db->from('jil_pocjdetail');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id= jil_pocjdetail.pocd_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query5= $this->db->get()->row_object();
$row->pocj_total = $query5->pocjtotal;
$this->db->select('count(jil_pojmdetail.pojd_requirementid) as pojmtotal');
$this->db->from('jil_pojmdetail');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id= jil_pojmdetail.pojd_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query6= $this->db->get()->row_object();
$row->pojm_total = $query6->pojmtotal;
$data[] = $row;
}
return $data;
}
return false;
}
$this->db->select('count(jil_quotemjdetail.qud_requirementid) as quotemjtotal');
$this->db->from('jil_quotemjdetail');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id=jil_quotemjdetail.qud_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query3= $this->db->get()->row_object();
$row->quotemj_total = $query3->quotemjtotal;
$this->db->select('count(jil_quotejcdetail.qud_requirementid) as quotejctotal');
$this->db->from('jil_quotejcdetail');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id= jil_quotejcdetail.qud_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query4= $this->db->get()->row_object();
$row->quotejc_total = $query4->quotejctotal;
$this->db->select('count( jil_pocjdetail.pocd_requirementid) as pocjtotal');
$this->db->from('jil_pocjdetail');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id= jil_pocjdetail.pocd_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query5= $this->db->get()->row_object();
$row->pocj_total = $query5->pocjtotal;
$this->db->select('count(jil_pojmdetail.pojd_requirementid) as pojmtotal');
$this->db->from('jil_pojmdetail');
$this->db->join('jil_requirements', 'jil_requirements.rqm_id= jil_pojmdetail.pojd_requirementid', 'left');
$this->db->where('jil_requirements.rqm_id',$row->rqm_id);
$query6= $this->db->get()->row_object();
$row->pojm_total = $query6->pojmtotal;
$data[] = $row;
}
return $data;
}
return false;
}
First you have to load the ignited dataTables library.
$this->load->library('datatables');
OR
add it to Autoloader for automatic loading when your Codeigniter application starts.
After that, change all
$this->db->
in your queries to
$this->datatables
Finally you have to use this to encode the data in json array
$this->datatables->generate();
Lemme know if i can still be of help
UPDATE
public function fetch_data() {
$this->datatables->from('jil_requirements');
$this->datatables->join('jil_users', 'jil_requirements.rqm_userid=jil_users.usr_id', 'left');
$this->datatables->join('jil_merchants', 'jil_requirements.rqm_createdempid=jil_merchants.mer_id', 'left');
$this->datatables->where('jil_requirements.rqm_permission!=', '4');
$this->datatables->order_by("jil_requirements.rqm_id", "desc");
$query = $this->datatables->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$this->datatables->select('count(jil_mrorfq.rfq_requirementid) as total');
$this->datatables->from('jil_mrorfq');
$this->datatables->join('jil_requirements', 'jil_requirements.rqm_id=jil_mrorfq.rfq_requirementid', 'left');
$this->datatables->where('jil_requirements.rqm_id',$row->rqm_id);
$query2= $this->datatables->get()->row_object();
$row->total_count = $query2->total;
$this->datatables->select('count(jil_quotemjdetail.qud_requirementid) as quotemjtotal');
$this->datatables->from('jil_quotemjdetail');
$this->datatables->join('jil_requirements', 'jil_requirements.rqm_id=jil_quotemjdetail.qud_requirementid', 'left');
$this->datatables->where('jil_requirements.rqm_id',$row->rqm_id);
$query3= $this->datatables->get()->row_object();
$row->quotemj_total = $query3->quotemjtotal;
$this->datatables->select('count(jil_quotejcdetail.qud_requirementid) as quotejctotal');
$this->datatables->from('jil_quotejcdetail');
$this->datatables->join('jil_requirements', 'jil_requirements.rqm_id= jil_quotejcdetail.qud_requirementid', 'left');
$this->datatables->where('jil_requirements.rqm_id',$row->rqm_id);
$query4= $this->datatables->get()->row_object();
$row->quotejc_total = $query4->quotejctotal;
$this->datatables->select('count( jil_pocjdetail.pocd_requirementid) as pocjtotal');
$this->datatables->from('jil_pocjdetail');
$this->datatables->join('jil_requirements', 'jil_requirements.rqm_id= jil_pocjdetail.pocd_requirementid', 'left');
$this->datatables->where('jil_requirements.rqm_id',$row->rqm_id);
$query5= $this->datatables->get()->row_object();
$row->pocj_total = $query5->pocjtotal;
$this->datatables->select('count(jil_pojmdetail.pojd_requirementid) as pojmtotal');
$this->datatables->from('jil_pojmdetail');
$this->datatables->join('jil_requirements', 'jil_requirements.rqm_id= jil_pojmdetail.pojd_requirementid', 'left');
$this->datatables->where('jil_requirements.rqm_id',$row->rqm_id);
$query6= $this->datatables->get()->row_object();
$row->pojm_total = $query6->pojmtotal;
echo $this->datatables->generate();
}
Use this in your controller and see if its working
public function fetch_data()
{
$this->load->library("datatables");
$query = $this->datatables
->select('jil_requirements.*,count(jil_mrorfq.rfq_requirementid) as total,count(jil_quotemjdetail.qud_requirementid) as quotemjtotal,count(jil_quotejcdetail.qud_requirementid) as quotejctotal,count( jil_pocjdetail.pocd_requirementid) as pocjtotal,count(jil_pojmdetail.pojd_requirementid) as pojmtotal')
->from('jil_requirements')
->join('jil_users', 'jil_requirements.rqm_userid=jil_users.usr_id', 'left')
->join('jil_merchants', 'jil_requirements.rqm_createdempid=jil_merchants.mer_id', 'left')
->join('jil_mrorfq', 'jil_mrorfq.rfq_requirementid = jil_requirements.rqm_id', 'left')
->join('jil_quotemjdetail', 'jil_quotemjdetail.qud_requirementid = jil_requirements.rqm_id', 'left')
->join('jil_pocjdetail', 'jil_pocjdetail.pocd_requirementid = jil_requirements.rqm_id', 'left')
->join('jil_pojmdetail', 'jil_pojmdetail.pojd_requirementid = jil_requirements.rqm_id', 'left')
->where('jil_requirements.rqm_permission!=', '4');
echo $this->datatables->generate();
}
Related
I have to lots of paginations one lot is for my user's results and the other is for my question results.
When I am on link 3 on my question results it also switches the results on users list pagination.
Question if I click on the questions pagination links how can I make sure it does not affect the results of the user's list.
I have tried this Best way to do multiple pagination on one page in codeigniter does not work
As you can see in image below because I am on questions list page 3 it has effected the users list
<?php
class Dashboard extends MY_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model('user/user_model');
$this->load->model('forum/question_model');
$this->load->library('pagination');
}
public function index() {
$this->data['title'] = 'Dashboard';
$this->data['is_logged'] = $this->session->userdata('is_logged');
$config1['base_url'] = base_url('dashboard/');
$config1['total_rows'] = $this->user_model->total_users();
$config1['per_page'] = 2;
$config1['uri_segment'] = 2;
$config1['num_links'] = 200;
$config1['use_page_numbers'] = FALSE;
$config1['prefix'] = 'u_';
$pagination1 = new CI_Pagination();
$pagination1->initialize($config1);
$this->data['pagination1'] = $pagination1->create_links();
$page_segment1 = explode('_', $this->uri->segment(2));
$page1 = ($this->uri->segment(2)) ? $page_segment1[1] : 0;
$this->data['users'] = array();
$users = $this->user_model->get_users($config1['per_page'], $page1);
foreach ($users as $user) {
$this->data['users'][] = array(
'user_id' => $user['user_id'],
'username' => $user['username'],
'status' => ($user['status']) ? 'Enabled' : 'Disabled',
'warning' => '0' . '%',
'date' => date('d-m-Y H:i:s A', $user['date_created_on']),
'href' => site_url('user/profile/') . $user['user_id']
);
}
// Questions Pagination & Results
$config2['base_url'] = base_url('dashboard/');
$config2['total_rows'] = $this->question_model->total_questions();
$config2['per_page'] = 2;
$config2['uri_segment'] = 2;
$config2['num_links'] = 200;
$config2['use_page_numbers'] = FALSE;
$config2['prefix'] = 'q_';
$pagination2 = new CI_Pagination();
$pagination2->initialize($config2);
$this->data['pagination2'] = $pagination2->create_links();
$page_segment2 = explode('_', $this->uri->segment(2));
$page2 = ($this->uri->segment(2)) ? $page_segment2[1] : 0;
$this->data['questions'] = array();
$questions = $this->question_model->get_questions($config2['per_page'], $page2);
foreach ($questions as $question) {
$this->data['questions'][] = array(
'user_id' => $question['user_id'],
'title' => $question['title']
);
}
$this->data['navbar'] = $this->load->view('common/navbar', $this->data, TRUE);
$this->data['header'] = $this->load->view('common/header', $this->data, TRUE);
$this->data['footer'] = $this->load->view('common/footer', '', TRUE);
$this->load->view('common/dashboard', $this->data);
}
}
Question Model
<?php
class Question_model extends CI_Model {
public function get_questions($limit, $start) {
$this->db->select('*');
$this->db->from('questions q');
$this->db->join('users u', 'u.user_id = q.user_id', 'left');
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result_array();
}
public function total_questions() {
return $this->db->count_all("questions");
}
}
Users Model
<?php
class User_model extends CI_Model {
public function get_users($limit, $start) {
$this->db->select('u.status, u.date_created_on, ud.*');
$this->db->from('users u', 'left');
$this->db->join('users_userdata ud', 'ud.user_id = u.user_id', 'left');
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result_array();
}
public function total_users() {
return $this->db->count_all("users");
}
}
I have these two functions below
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
// $this->db->group_by('p.user_id');
$query = $this->db->get();
return $query->result_array();
}
Results Output
SELECT * FROM `post` WHERE `post_id` = '1' AND `reply_id` = '0' AND `user_id` = '2'
SELECT * FROM `post` WHERE `post_id` = '3' AND `reply_id` = '1' AND `user_id` = '1'
SELECT * FROM `post` WHERE `post_id` = '5' AND `reply_id` = '1' AND `user_id` = '1'
Total Posts Function
public function total_posts_by_user($user_id, $reply_id, $post_id) {
$this->db->from('post');
$this->db->where('post_id', $post_id);
$this->db->where('reply_id', $reply_id);
$this->db->where('user_id', $user_id);
// $this->db->group_by('user_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
}
}
The total_posts_by user gets the number of post shown in image below
Question As you can see there are 2 admin row results showing. But I
would like them to be combined so it will just say row for admin and 2
posts.
I have tried using group_by() on get_post but dos not work
Controller
<?php
class Who_replied extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$data['posts'] = array();
$results = $this->get_posts();
foreach ($results as $result) {
$data['posts'][] = array(
'username' => $result['username'],
'total' => $this->total_posts_by_user($result['user_id'], $result['reply_id'], $result['post_id'])
);
$this->total_posts_by_user($result['user_id'], $result['reply_id'], $result['post_id']);
echo $this->db->last_query() . '</br>';
}
$data['total_posts'] = $this->total_posts();
return $this->load->view('default/template/forum/categories/who_replied_view', $data);
}
}
Use left join in first method because current it is using inner join. After that use group by
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id','left');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
$this->db->group_by('p.post_id');
$query = $this->db->get();
return $query->result_array();
}
and try. If still face same issue double check whether there are same TWO username admin
** Have you tried DISCTINCT?
hope it will help
I have found my solution from here using COUNT(p.user_id) AS total
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username COUNT(p.user_id) AS total');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
$this->db->group_by('p.user_id');
$query = $this->db->get();
return $query->result_array();
}
I have made a query that gets customer's orders. Can I get customer gender based on this query? If not, how can I get customer gender? This is the code I have so far:
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$productId = 297;
$orders = Mage::getModel('sales/order')->getCollection();
$orders
->getSelect()
->joinLeft(
array(
'order_item' =>Mage::getSingleton('core/resource')->getTableName('sales/order_item')),
'order_item.order_id = main_table.entity_id',
array('product_id'=>'product_id'))
->where('product_id=?', $productId)
->group('main_table.entity_id')
->order('main_table.entity_id DESC');
$fields = "date,company,name,country,city,address,postcode,itemname,quantity,price,sku \n";
foreach($orders as $order):
$order->getData();
$order->getIncrementId();
$billingAddress = $order->getBillingAddress();
$shippingAddress = $order->getShippingAddress();
$billingStreet = $billingAddress->getStreet();
$countryCode = $billingAddress->getCountry();
$country = Mage::getModel('directory/country')->loadByCode($countryCode);
$fields .=
date('Y-m-d',strtotime($order->getCreatedAt())).','.
$billingAddress->getCompany().','.
$billingAddress->getName().','.
$country->getName().','.
$billingAddress->getCity().','.
$billingStreet[0].','.
$billingAddress->getPostcode().','.
$order->getShippingDescription() .',';
foreach ($order->getAllItems() as $itemId => $item):
$itemname = $item->getName();
$itemname = str_replace('&', " ", $itemname);
$fields .=
$itemname. ','.
$item->getQtyOrdered().','.
$item->getPrice().','.
$item->getSku().',';
endforeach;
$fields = rtrim($fields, ',');
$fields .= "\n";
endforeach;
$name = date('d-m-Y-H-i-s');
$output = fopen('backend/assets/csv/' . $name . '.csv', 'w');
fwrite ($output,$fields);
fclose ($output);
foreach($orders as $order){
$customer = $order->getCustomer();
Mage::log($customer->getGender());
}
if this does not work then:
foreach($orders as $order){
$customer = $order->getCustomer();
$customerObj = Mage::getModel('customer/customer')->load( $customer->getEntityId());
Mage::log($customerObj->getGender());
}
I use codeigniter for my website, but I have a problem I have done script who returns rows from different tables. But it write me error Trying to get property of non-object. This is my code. Where is a problem?
$this->db->select('*');
$this->db->from('orders');
$this->db->where('order_id',$order_id);
$array_keys_values = $this->db->get();
$row = $array_keys_values->row();
$this->db->select('*');
$this->db->from('pacients');
$this->db->where('pacient_account_id',$row->order_pacient_id);
$array_keys_values2 = $this->db->get();
$row2 = $array_keys_values2->row();
$this->db->select('*');
$this->db->from('doctors');
$this->db->where('doctor_account_id',$doctor_id);
$array_keys_values3 = $this->db->get();
$row3 = $array_keys_values3->row();
Try
$this->db->select('*');
$this->db->from('orders');
$this->db->where('order_id',$order_id);
$array_keys_values = $this->db->get();
if ($array_keys_values->num_rows() > 0) {
foreach ($array_keys_values->result() as $row) {
// now you can work with $row
}
}
$this->db->select('*');
$this->db->from('pacients');
$this->db->where('pacient_account_id',$row->order_pacient_id);
$array_keys_values2 = $this->db->get();
if ($array_keys_values2->num_rows() > 0) {
foreach ($array_keys_values2->result() as $row2) {
// now you can work with $row2
}
}
$this->db->select('*');
$this->db->from('doctors');
$this->db->where('doctor_account_id',$doctor_id);
$array_keys_values3 = $this->db->get();
if ($array_keys_values3->num_rows() > 0) {
foreach ($array_keys_values3->result() as $row3) {
// now you can work with $row3
}
}
No row was returned. Use an if statement with a num_rows() > 0 to check
Is there an easy way to filter a product collection by multiple categories? To get all items in any of the listed categories? addCategoryFilter doesn't seem to allow an array.
Is the only way to get the collections for each category of interest separately then merge them?
I understand it used to be possible with something like
addAttributeToFilter('category_ids',array('finset'=>array('1','2')))
or similar, but that this is no longer possible since 1.4.
Note: I am using 1.6, and in case it's of any use, I'm using something like this:
$product = Mage::getModel('catalog/product');
$_productCollection = $product->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status',1)
->addStoreFilter();
Here's a method that doesn't require modifications to core.
It's taken from this post with the addition of the 'group' clause to handle duplicate product records.
$categories = array(7,45,233);
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->joinField('category_id',
'catalog/category_product',
'category_id',
'product_id=entity_id',
null,
'left')
->addAttributeToFilter('category_id', array('in' => $categories));
$collection->getSelect()->group('e.entity_id');
The way Magento works now, is to get the Store, and on the store, you can get the categories from the storecollection like $oStoreCollection->addCategoryFilter(array('1','2'));
I came across a solution that might help you, found here at:
http://www.magentocommerce.com/boards/&/viewthread/201114/#t329230
The code they use, looks like this:
Override Mage/Catalog/Model/Resource/Eav/Mysql4/Product/Collection, and add the following methods:
public function addCategoriesFilter($categories)
{
$this->_productLimitationFilters['category_ids'] = $categories;
if ($this->getStoreId() == Mage_Core_Model_App::ADMIN_STORE_ID) {
$this->_applyZeroStoreProductLimitations();
} else {
$this->_applyProductLimitations();
}
return $this;
}
protected function _applyProductLimitations()
{
$this->_prepareProductLimitationFilters();
$this->_productLimitationJoinWebsite();
$this->_productLimitationJoinPrice();
$filters = $this->_productLimitationFilters;
// Addition: support for filtering multiple categories.
if (!isset($filters['category_id']) && !isset($filters['category_ids']) && !isset($filters['visibility'])) {
return $this;
}
$conditions = array(
'cat_index.product_id=e.entity_id',
$this->getConnection()->quoteInto('cat_index.store_id=?', $filters['store_id'])
);
if (isset($filters['visibility']) && !isset($filters['store_table'])) {
$conditions[] = $this->getConnection()
->quoteInto('cat_index.visibility IN(?)', $filters['visibility']);
}
// Addition: support for filtering multiple categories.
if (!isset($filters['category_ids'])) {
$conditions[] = $this->getConnection()
->quoteInto('cat_index.category_id=?', $filters['category_id']);
if (isset($filters['category_is_anchor'])) {
$conditions[] = $this->getConnection()
->quoteInto('cat_index.is_parent=?', $filters['category_is_anchor']);
}
} else {
$conditions[] = $this->getConnection()->quoteInto('cat_index.category_id IN(' . implode(',', $filters['category_ids']) . ')', "");
}
$joinCond = join(' AND ', $conditions);
$fromPart = $this->getSelect()->getPart(Zend_Db_Select::FROM);
if (isset($fromPart['cat_index'])) {
$fromPart['cat_index']['joinCondition'] = $joinCond;
$this->getSelect()->setPart(Zend_Db_Select::FROM, $fromPart);
}
else {
$this->getSelect()->join(
array('cat_index' => $this->getTable('catalog/category_product_index')),
$joinCond,
array('cat_index_position' => 'position')
);
}
$this->_productLimitationJoinStore();
Mage::dispatchEvent('catalog_product_collection_apply_limitations_after', array(
'collection' => $this
));
return $this;
}
protected function _applyZeroStoreProductLimitations()
{
$filters = $this->_productLimitationFilters;
// Addition: supprot for filtering multiple categories.
$categoryCondition = null;
if (!isset($filters['category_ids'])) {
$categoryCondition = $this->getConnection()->quoteInto('cat_pro.category_id=?', $filters['category_id']);
} else {
$categoryCondition = $this->getConnection()->quoteInto('cat_pro.category_id IN(' . implode(',', $filters['category_ids']) . ')', "");
}
$conditions = array(
'cat_pro.product_id=e.entity_id',
$categoryCondition
);
$joinCond = join(' AND ', $conditions);
$fromPart = $this->getSelect()->getPart(Zend_Db_Select::FROM);
if (isset($fromPart['cat_pro'])) {
$fromPart['cat_pro']['joinCondition'] = $joinCond;
$this->getSelect()->setPart(Zend_Db_Select::FROM, $fromPart);
}
else {
$this->getSelect()->join(
array('cat_pro' => $this->getTable('catalog/category_product')),
$joinCond,
array('cat_index_position' => 'position')
);
}
return $this;
}
It then gets called like this:
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->distinct(true) // THIS IS WHAT YOU NEED TO ADD
->addCategoriesFilter($category->getAllChildren(true)); // Make sure you don't forget to retrieve your category here.
HTH
If you want to filter on multiple categories, using AND (so a product must be in categorie A, B and C to show up, you need to have multiple joins:
$products = Mage::getModel('catalog/product')->getCollection()
->joinField('category_id_1', 'catalog/category_product', 'category_id', 'product_id=entity_id', null, 'left')
->joinField('category_id_2', 'catalog/category_product', 'category_id', 'product_id=entity_id', null, 'left')
->addAttributeToFilter('category_id_1', array('eq' => 358))
->addAttributeToFilter('category_id_2', array('eq' => 252))
// etc...
;
I managed to resolve this (after much trial and error) with the following code:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('status', 1);
$collection->addAttributeToSelect(array('name','sku','price','small_image'));
// Filter by multiple categories
$collection->joinField('category_id','catalog/category_product','category_id','product_id=entity_id',null,'left');
$data_cats = $this->getRequest()->getParam('categories');
// Or $data_cats = array(85,86,87,88);
$filter_cats = array();
foreach ($data_cats as $value_cats) {
$filter_cats[] = array(
'attribute' => 'category_id',
'finset' => $value_cats
);
}
$collection->addAttributeToFilter($filter_cats);
Hope this helps someone ;)
Magento 1.8.0.0;
Flat catalog enabled in admin;
Make sure you've cached the block in which you'll place this;
Don't add this in paid themes ..
The inner join hard-coded here reproduces this:
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
without 'cat_index.category_id=2'
$category = Mage::getModel('catalog/category')->load(100);
$allChildsIds = $category->getAllChildren($category);
$visibility = Mage::getModel('catalog/product_visibility');
$collection = Mage::getResourceModel('catalog/product_collection');
$collection = $this->_addProductAttributesAndPrices($collection)
->addStoreFilter()
->setFlag('do_not_use_category_id', true)
->setFlag('disable_root_category_filter', true)
->addAttributeToSort('created_at', 'desc');
$whereCategoryCondition = $collection->getConnection()
->quoteInto('cat_index.category_id IN(?) ', $allChildsIds);
$collection->getSelect()->where($whereCategoryCondition);
$conditions = array();
$conditions[] = "cat_index.product_id = e.entity_id";
$conditions[] = $collection->getConnection()
->quoteInto('cat_index.store_id = ? ', Mage::app()->getStore()->getStoreId());
$conditions[] = $collection->getConnection()
->quoteInto('cat_index.visibility IN(?) ', $visibility->getVisibleInCatalogIds());
$collection->getSelect()->join(
array('cat_index' => $collection->getTable('catalog/category_product_index')),
join(' AND ', $conditions),
array()
);
$collection
->setPageSize(3)
->setCurPage(1);
$collection->load();
Filter Product Collection using multiple category ids
$all_categories = array('3','13','113');
$productCollection = Mage::getModel('catalog/product')->getCollection();
$productCollection->joinField('category_id', 'catalog/category_product', 'category_id',
'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('type_id', array('eq' => 'simple'))
->addAttributeToFilter('category_id', array($all_categories));
foreach($productCollection as $product)
{
echo $product->getId() .$product->getName() . "<br/>";
}
You can remove the condition for product type i.e type_id or modify it as per requirement.
Reference: https://www.fmeextensions.com/blog/get-product-collection-by-category-id-magento-2/
$ids = [1,2,3,4,5,6,7];
$collectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
$products = $collectionFactory->addAttributeToSelect('*')
->addCategoriesFilter(['in' => $ids]);
foreach ($products as $product) {
echo $product->getId() . "<br />";
echo $product->getName() . "<br />";
echo $product->getProductUrl() . "<br />";
}