I want to get product list with category and category listed as in two different columns in woocommerce - categories

i want to get product list with parent category and subcategory as seperate in the result in woocommerce
This code I have tried
SELECT
p.ID,
p.post_title,
`post_content`,
`post_excerpt`,
t.name AS product_category,
t.term_id AS product_id,
t.slug AS product_slug,
tt.term_taxonomy_id AS tt_term_taxonomia,
tr.term_taxonomy_id AS tr_term_taxonomia,
MAX(CASE WHEN pm1.meta_key = '_price' then pm1.meta_value ELSE NULL END) as price,
MAX(CASE WHEN pm1.meta_key = '_regular_price' then pm1.meta_value ELSE NULL END) as
regular_price,
MAX(CASE WHEN pm1.meta_key = '_sale_price' then pm1.meta_value ELSE NULL END) as sale_price,
MAX(CASE WHEN pm1.meta_key = '_sku' then pm1.meta_value ELSE NULL END) as sku
FROM wp_posts p
LEFT JOIN wp_postmeta pm1 ON pm1.post_id = p.ID
LEFT JOIN wp_term_relationships AS tr ON tr.object_id = p.ID
JOIN wp_term_taxonomy AS tt ON tt.taxonomy = 'product_cat' AND tt.term_taxonomy_id =
tr.term_taxonomy_id
JOIN wp_terms AS t ON t.term_id = tt.term_id
WHERE p.post_type in('product', 'product_variation') AND p.post_status = 'publish' AND
p.post_content <> ''
GROUP BY p.ID,p.post_title
Any Idea,thanks in advance

If you want to get a list of products with parent_category and sub_category in an array format, then you can use WordPress WP_Query. Try following code snippet.
<?php
// fetch all products from woocommerce
$args = array('post_type' => 'product', 'posts_per_page' => -1);
$loop = new WP_Query($args);
$product_list_array = []; // result array with product_id,parent_category and sub_category
while ($loop->have_posts()) : $loop->the_post();
global $product;
$product_id = $product->get_id();
$result = []; $parent_cats = []; $sub_cats = [];
$result['product_id'] = $product_id;
$categories = get_the_terms($product_id, 'product_cat'); // get category list of a product
foreach ($categories as $category) {
// check if it is a parent or child
if ($category->parent == 0) {
$parent_cats[] = $category->name;
} else {
$parent_cat = get_term_by('id', $category->parent, 'product_cat'); // to get parent category name
$sub_cats[] = $category->name;
$parent_cats[] = $parent_cat->name;
}
}
// if multiple category exist then join them to a string
$result['parent_category'] = implode(" | ", array_unique($parent_cats));
$result['sub_category'] = implode(" | ", array_unique($sub_cats));
$product_list_array[] = $result;
endwhile;
?>
The $product_list_array should contain product_id,parent_category and sub_category.

Related

How can i get rank or position base highest ' gpa' and 'total' into database rows data in codeigniter?

How can i get rank or position base highest ' gpa' and 'total' into database rows data in codeigniter?
public function fetchData() {
$data = array();
$data['fetch_data'] = $this->excel_data_insert_model->fetch_data();
$result = $data['fetch_data']->result();
foreach ($result as $row) {
//echo $row.'<br/>';
$id = $row->id;
$p_student_id = $row->stu_id;
$p_section = $row->section;
$p_gpa = $row->gpa;
$p_total = $row->total;
$x = 0;
}
}
My Answer to your raw query could be this:
Select column_name1, column_name2, MAX(gpa),MAX(total) from tbl_v1 ORDER by gpa, total desc
Also for CI
$query=$this->db->select('column_name1, column_name2, MAX(gpa),MAX(total)')->order_by('gpa,total','desc'‌​)->get('tbl_v1');
return $query;

Why sphinx does not return attributes name?

I use two indexes for search in Sphinx:
#users
source users : lsParentSource
{
sql_query_range = SELECT MIN(idDetailToUsers), MAX(idDetailToUsers) FROM detailtousers
sql_query = SELECT idDetailToUsers as id, 1000 as type, UsersTypeAccount, idDetailToUsers, SpecializationName, DetailToUsersName, DetailToUsersPhoto, city, country FROM detailtousers join users ON users.idUsers = detailtousers.idDetailToUsers left join usersspecialization ON usersspecialization.UsersSpecializationIdUser = detailtousers.idDetailToUsers left join specializationtousers ON specializationtousers.idSpecialization = usersspecialization.UsersSpecializationIdSpecialization WHERE idDetailToUsers >= $start AND idDetailToUsers <= $end GROUP BY idDetailToUsers
sql_attr_uint = type
sql_attr_uint = idDetailToUsers
sql_attr_uint = UsersTypeAccount
sql_field_string = SpecializationName
sql_field_string = DetailToUsersName
sql_field_string = DetailToUsersPhoto
sql_attr_uint = city
sql_attr_uint = country
sql_query_info = SELECT idDetailToUsers, DetailToUsersName, UsersTypeAccount, SpecializationName, DetailToUsersPhoto, city, country \
FROM detailtousers WHERE idDetailToUsers = $id
sql_ranged_throttle = 0
}
#medical
source medical : lsParentSource
{
sql_query_range = SELECT MIN(idMedicalFacilities), MAX(idMedicalFacilities) FROM medicalfacilities
sql_query = SELECT idMedicalFacilities as id, 2000 as type, idMedicalFacilities, MedicalFacilitiesName, MedicalFacilitiesPhoto, city, country FROM medicalfacilities WHERE idMedicalFacilities >= $start AND idMedicalFacilities <= $end
sql_attr_uint = type
sql_attr_uint = MedicalFacilitiesIdUser
sql_attr_uint = idMedicalFacilities
sql_field_string = MedicalFacilitiesName
sql_field_string = MedicalFacilitiesPhoto
sql_attr_uint = city
sql_attr_uint = country
sql_query_info = SELECT MedicalFacilitiesIdUser, MedicalFacilitiesName, MedicalFacilitiesPhoto FROM medicalfacilities WHERE idMedicalFacilities = $id
sql_ranged_throttle = 0
}
If use an index users only it returns me all attributes specified in select query.
But if use a two indexes the sphinx does not return attributes.
What is reason?
Result for index users:
array(1) {
[533]=>
array(2) {
["weight"]=>
int(1)
["attrs"]=>
array(0) {
}
}
}
Result for index medical:
array(5) {
[451]=>
array(2) {
["weight"]=>
int(2)
["attrs"]=>
array(0) {
}
}
[444]=>
array(2) {
["weight"]=>
int(1)
["attrs"]=>
array(0) {
}
}
Sphinx only returns attributes common to the indexes in the query. you have different names.
You might be able to use the EXISTS function from sphinxQL in the SetSelect, but never tried.
Easiest is just to use the same attribute names.

Hide Bundle Product if one of the Children is outofstock

how can i filter product collection so it will return the collection which does not contain bundle product whose one of children is Out of stock.
Got the solution for my question
$collection = Mage::getResourceModel('catalog/product_collection');
$bundled_items = array();
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
foreach ($collection->getAllIds() as $proId)
{
$bundled_product=Mage::getModel('catalog/product')->load($proId);
if($bundled_product->getTypeId()=="bundle")
{
$selectionCollection = $bundled_product->getTypeInstance(true)->getSelectionsCollection(
$bundled_product->getTypeInstance(true)->getOptionsIds($bundled_product), $bundled_product
);
foreach($selectionCollection as $option)
{
$product = Mage::getModel('catalog/product')->load($option->getProductId());
$stockItem = $product->getStockItem();
if($product->stock_item->is_in_stock == 0)
{
$bundled_items[] = $proId;
}
}
}
}
if(isset($bundled_items) && !empty($bundled_items))
{
$collection->addFieldToFilter('entity_id',array( 'nin' => array_unique($bundled_items)));
}
Alternate answer
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
$otherProductIds = $collection->getAllIds();
//get only bundle
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('type_id','bundle');
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
$bundleIds = $collection->getAllIds();
//checking bundle associate product stock status
$readAdapter = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $readAdapter->select()
->from(array('css'=> Mage::getSingleton('core/resource')->getTableName('cataloginventory/stock_status')),array())
->join(
array('bs'=> Mage::getSingleton('core/resource')->getTableName('bundle/selection')),
'bs.product_id = css.product_id',
array('parent_product_id')
)
->where('bs.parent_product_id IN (?)',$bundleIds)
->where('css.stock_status = 0')
->group('bs.parent_product_id');
$excludeBundleIds = $readAdapter->fetchCol($select);//return outstock associated products parent ids
$allIds = array_merge($otherProductIds, array_diff($bundleIds,$excludeBundleIds));
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('entity_id',array( 'in' => $allIds))
->addMinimalPrice()
->addFinalPrice();
return $collection
Hope this will helpful

Querying for dates in doctrine

I have a table called active_plans in which there are two columns: activated_date and last_billed_at. Basically, I want to create a query that looks at these two columns like this:
select all from active_plans
where last_billed_at = null AND activated_date + 1 month = today,
or if last_billed_at + 1 month = today.
I can't seem to figure out how to do this, though.
I wound up doing something a lot different:
public function getBillToday()
{
$activePlans = $this->entityManager
->createQuery('SELECT adp FROM adp
WHERE adp.activationDate IS NOT NULL')
->getResult();
$data = array();
foreach ($activePlans as $plan) {
$recur = $plan->getPlan()->getRecurringInMonths();
$nextBillTime = strtotime('-'.$recur.' months', time());
$nextBill = date('Y-m-d', $nextBillTime);
$activationDate = $plan->getActivationDate();
$lastBilledAt = $plan->getLastBilledAt() != NULL ? $plan->getLastBilledAt()->format('Y-m-d') : 0;
if ($activationDate == $nextBill || $lastBilledAt == $nextBill) {
$data[] = $plan->getId();
}
}
return $data;
}

How do I do this sql query in Zend?

How do I do this sql query in Zend Framework, I need to some how do this in the PDO context I think? I tried ->query but not sure if I am getting this right. The three variables are user_id and to and from date.
SELECT
ss.subcategory_id,
ss.subcategory_name,
ss.subcategory_issaving,
IFNULL(SUM(m.mv_monthly_total),0) AS expendsum
FROM
(SELECT
s.subcategory_id,
s.subcategory_name,
s.subcategory_issaving
FROM
subcategory s
WHERE
s.subcategory_isexpend = 'Y'
AND
s.subcategory_issaving = 'Y') ss
LEFT JOIN
mv_monthly m
ON ss.subcategory_id = m.mv_monthly_subcategory_id
AND m.mv_monthly_user_id = 2
AND m.mv_monthly_month >= '2010-01-01'
AND m.mv_monthly_month <= '2020-01-01'
GROUP BY
ss.subcategory_id,
ss.subcategory_name,
ss.subcategory_issaving
ORDER BY
ss.subcategory_issaving DESC,
expendsum;
I have tried the following with no luck
$db = Zend_Db_Table::getDefaultAdapter();
$dbExpr1 = new Zend_Db_Expr("s.subcategory_id, s.subcategory_name, s.subcategory_issaving");
$dbExpr2 = new Zend_Db_Expr("ss.subcategory_id, ss.subcategory_name, ss.subcategory_issaving, IFNULL(SUM(m.mv_monthly_total),0) AS expendsum");
$select = $db->select()
->from(
array(
'ss' => new Zend_Db_Expr(
'('. $db->select()
->from(array("s" => "subcategory"), $dbExpr1)
->where("s.subcategory_isexpend = 'Y'")
->where("s.subcategory_issaving = 'Y'") .')'
)
),
$dbExpr2
)
->joinLeft(array("m" => "mv_monthly"), "ss.subcategory_id = m.mv_monthly_subcategory_id")
->where("m.mv_monthly_user_id = ?", $user_id)
->where("m.mv_monthly_month >= ?", $fromMonth)
->where("m.mv_monthly_month <= ?", $toMonth)
->group(array("ss.subcategory_id","ss.subcategory_name","ss.subcategory_issaving"))
->order(array("ss.subcategory_issaving DESC", "expendsum"));
$row = $db->fetchAll($select);
For such a complex query, you can just execute it directly rather than using the object oriented approach as it gets fairly complicated with a query like that.
Try something like this, replacing my query with yours, and binding your variables into the query:
$db = Zend_Db_Table::getDefaultAdapter();
$stmt = new Zend_Db_Statement_Pdo($db, 'SELECT a, b, c FROM a WHERE username = ? AND date = ?');
try {
$res = $stmt->execute(array($user_id, $fromMonth));
if ($res) {
$rows = $stmt->fetchAll();
}
} catch (Zend_Db_Statement_Exception $dbex) {
// log Query failed with exception $dbex->getMessage();
}
If you prefer to use the object oriented approach, or need to because some parts of the query will be conditional, I usually build by subqueries up first as their own select, and you can simply embed those in to the main query with the select object for the subquery.
Here is what I mean by that:
$subselect = $this->getDbTable()
->select()
->from('mytable', array('time' => 'max(time)', 'id'))
->where('id IN (?)', $serialNumbers)
->group('id');
$select = $this->getDbTable()
->select()
->setIntegrityCheck(false)
->from('mytable')
->join('other', 'mytable.id = other.id', array('label'))
->join(array('dt' => $subselect),
'(mytable.time, mytable.id) = (dt.time, dt.id)', '');