Querying for dates in doctrine - date

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

Related

Magento 2 - Update Product stock and Price Programmatically for multiple stores

I'm getting data from the CSV file and according to SKU file load the product.
We are getting 30 products from the CSV file and update those product data in Magento.
We have set up cron every 5 minutes and after 5 minutes it will get the next 30 products and update.
The starting process script is working fine. But after the sometime script is going to be slow and it will take time to update the product.
So, the next cron is running at on the same time there are lots of scripts are running on the server, and the server load will increase.
After taking so much load on the server website going to be slow.
Can you please let me know the way so product updating process will be consistent and time will not so much vary.
public function execute()
{
$data = array of csv file data;
$sql = "Select value FROM " . $tableName . " where path='catalog/product/update_cron' and scope_id=0";
$result = $connection->fetchAll($sql);
$update_cron = $result[0]['value'];
$total_products = count($data);
if ($total_products == $update_cron) {
$this->configWriter->save('catalog/product/update_cron_status', '1', 'default', '0'); // inject Magento\Store\Model\ScopeInterface;
exit;
}
if ($update_cron != '' && $update_cron != 0) {
$data = array_slice($data, (int)$update_cron, 30);
} else {
$update_cron = 0;
$data = array_slice($data, 0, 30);
}
$current_date = date("m/d/Y");
$i = 0;
foreach ($data as $key => $value) {
/*********************************************Update Product Price********************************************************/
if ($value['Artikel'] != '') {
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product_id = $product->getIdBySku($value['Artikel']);
if (!empty($product_id)) {
/************************Update Product Price for all Stores**************************************/
$price_b2b = str_replace(',', '.', (string) $value['Verkoopprijs']);
$price_b2c = str_replace(',', '.', (string) $value['Numeriek1']);
$price_club = str_replace(',', '.', (string) $value['Numeriek2']);
//$special_price_b2b = str_replace(',', '.', (string) $value['Numeriek3']);
$productActionObject = $objectManager->create('Magento\Catalog\Model\Product\Action');
$productActionObject->updateAttributes(array($product_id),
array(
'name' => $value['Artikel'],
'ean_code'=>$value['Barcode'],
'price'=>$price_b2c,
'price_wholesale'=>$price_b2b,
'price_clubs'=>$price_club,
'description'=>$value['Omschrijving Engels'],
),0
);
/* if ($value['Boolean1'] == 'True') {
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => $special_price_b2b, 'special_from_date' => $current_date), 4);
} else { */
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => '', 'special_from_date' => ''), 4);
//}
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_club), 7);
/*********************************************Inventory Update********************************************************/
$stockRegistry = $objectManager->create('Magento\CatalogInventory\Api\StockRegistryInterface');
$sku = $value['Artikel'];
if($sku != '')
{
$qty = round(str_replace(',', '', (string) $value['Stock']));
$stockItem = $stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($value['Stock']);
$stockItem->setIsInStock((int) ($qty > 0)); // this line
$stockRegistry->updateStockItemBySku($sku, $stockItem);
}
/*****************************************************************************************************/
}
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
else {
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
}
die('records completed');
}
}
die('stop');
}
Thanks in advance

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;

change mysqli check exit and insert into pdo statement

i want to change my mysqli check exist and insert into pdo.. my statement look like below:
<?php
$addSearch = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $search);
if ($CheckMusic = $mysqli->query("SELECT * FROM search WHERE term='$addSearch'")) {
$CheckRow = mysqli_fetch_array($CheckMusic);
$CheckId = $CheckRow['id'];
$CheckCnt = $CheckMusic->num_rows;
$CheckMusic->close();
} else {
printf("Error: %s\n", $mysqli->error);
}
$Now = strtotime("now");
$addSearch = $mysqli->escape_string($addSearch);
if ($CheckCnt < 1) {
$mysqli->query("INSERT INTO search (term, datetime) VALUES('$addSearch','$Now') ") or die(mysqli_error());
} else {
$mysqli->query("UPDATE search SET datetime='$Now' WHERE id='$CheckId'") or die(mysqli_error());
}
?>
hope someone can help with sample if can ;q thanks for your advance!
<?php
$addSearch = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $search);
$CheckMusic = $mysqli->query("SELECT * FROM search WHERE term='$addSearch'");
$Now = strtotime("now");
if($CheckMusic->num_rows == 0){
$mysqli->query("INSERT INTO search (term, datetime) VALUES('$addSearch','$Now') ") or die(mysqli_error());
}else{
$CheckRow = mysqli_fetch_array($CheckMusic);
$CheckId = $CheckRow['id'];
$addSearch = $mysqli->escape_string($addSearch);
$mysqli->query("UPDATE search SET datetime='$Now' WHERE id='$CheckId'") or die(mysqli_error());
}
I hope it will work.

merge two Where with AND in zend 2

I have problem to merge two conditions in my query
public function GetInbox($user_id , $line_number = false , $seeall = false , $limit = 0,$SearchWhere = null)
{
if(!$SearchWhere)
$SearchWhere = new Where();
if(!$seeall)
{
$UsersLineTable = new UsersLinesTable($this->adapter);
$UsersLine = $UsersLineTable->fetchAll(array('user_id = ?' => $user_id,'owner_type = ?' => '1'));
if(!$UsersLine) return false;
$SearchWhere2 = new Where();
foreach ($UsersLine as $key => $value) {
$SearchWhere2->equalTo("recipient_number",$value['line_number'])
->or
->equalTo("recipient_number",'98'.$value['line_number'])
->or;
}
$Select = new Select();
$Select->where($SearchWhere2);
$Select->where($SearchWhere);
if($limit)
$Select->limit($limit);
$Select->order("receive_date DESC");
$MessageProvidersInboxTable = new MessageProvidersInboxTable($this->adapter);
return $MessageProvidersInboxTable->fetchBySelect($Select);
}else{
$MessageProvidersInboxTable = new MessageProvidersInboxTable($this->adapter);
return $MessageProvidersInboxTable->fetchAll($SearchWhere);
}
}
$SearchWhere is a Where class,
$SearchWhere2 is second conditions
In this case
$Select->where($SearchWhere2);
$Select->where($SearchWhere);
$select just contain $SearchWhere conditions.
I want this query
Where condition1 AND (condition2)
is that important that condition2 contain conditions include OR operand.
Sincerely
Try this, it should work. Writing without looking at zend\db code:
$where = new \Zend\Db\Sql\Where;
$where->addPredicate($SearchWhere, $where::OP_AND);
$where->addPredicate($SearchWhere2, $where::OP_AND);
$select->where($where);
Basically, Where object is a subclass of Predicate. So it should work as any other predicate.

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