Where by month in codeigniter - codeigniter

I have this code
$where = array('MONTH(c.cashDate)' => 'MONTH(NOW())');
$data['dataCash'] = $this->cash->cashList($where);
but it doesn't work, its create query like this
SELECT `c`.`cashId`, `c`.`cashDescription`, `c`.`cashDate`, `c`.`cashCategory`, `a`.`category`, `c`.`cashValue`, `t`.`typeid`, `t`.`type` FROM (`cash` c) LEFT JOIN `cashCategory` a ON `c`.`cashCategory` = `a`.`categoryId` LEFT JOIN `type` t ON `a`.`type` = `t`.`typeid` WHERE MONTH(c.cashDatee) = 'MONTH(NOW())' ORDER BY `c`.`cashDate` desc
when I try with phpmyadmin, it doesnt have a row
but when I remove ' from MONTH(NOW()) like this
SELECT `c`.`cashId`, `c`.`cashDescription`, `c`.`cashDate`, `c`.`cashCategory`, `a`.`category`, `c`.`cashValue`, `t`.`typeid`, `t`.`type` FROM (`cash` c) LEFT JOIN `cashCategory` a ON `c`.`cashCategory` = `a`.`categoryId` LEFT JOIN `type` t ON `a`.`type` = `t`.`typeid` WHERE MONTH(c.cashDatee) = MONTH(NOW()) ORDER BY `c`.`cashDate` desc
it works, how I call func in controller?
when you do this, it wont work
$where = array('MONTH(c.cashDate)' => MONTH(NOW()));

Just update your $where condition
$where = array('MONTH(c.cashDate)' => 'MONTH(NOW())');
into
$where = 'MONTH(c.cashDate) = MONTH(NOW())';

Related

Group Concatenation with Linq

I have this:
var lstAssignmentDetails =
(from t1 in _unitOfWork.ReferralDetailsRepository.Get()
.Where(m => (m.ChartStatusID == (int)Utility.ReferralChartStatus.NotStaffed
|| m.ChartStatusID == (int)Utility.ReferralChartStatus.Partially_Staffed
|| m.ChartStatusID == (int)Utility.ReferralChartStatus.Restaff)
&& m.IsDeleted == false).OrderByDescending(x => x.ReferralDetailsId)
join t2 in _unitOfWork.ReferralRepository.Get() on t1.ReferralId equals t2.ReferralId
join t3 in _unitOfWork.PatientRepository.Get() on t2.PatientId equals t3.PatientId
join t4 in _unitOfWork.ClientRepository.Get() on t2.ClientId equals t4.ClientID
join t5 in _unitOfWork.DisciplineRepository.Get() on t1.DesciplineID equals t5.DesciplineID
join t6 in _unitOfWork.UserRepository.Get() on t2.CreatedBy equals t6.UserID
join t7 in _unitOfWork.PersonRepository.Get() on t6.PersonID equals t7.PersonID
join rt in _unitOfWork.ReferralTherapistRepository.Get() on t2.ReferralId equals rt.ReferralId
join t in _unitOfWork.TherapistRepository.Get() on rt.TherapistId equals t.TherapistId
join u in _unitOfWork.UserRepository.Get() on t.UserId equals u.UserID
join p in _unitOfWork.PersonRepository.Get() on u.PersonID equals p.PersonID
select new ReferralTempModel()
{
ReferralId = t1.ReferralId,
ClientName = t4.ClientName,
PatientName = t3.LastName + "," + t3.FirstName,
RefferalDate = t2.RefferalDate,
DisciplineID = t1.DisciplineID,
ReferralDetailsId = t1.ReferralDetailsId,
PatientId = t2.PatientId,
ClientID = t4.ClientID,
DiscName = t5.DesciplineType,
IsRejected = t1.IsRejected,
CreatedBy = t7.LastName + "," + t7.FirstName,
ChartstatusId = t1.ChartStatusID.Value
}).ToList();
return lstAssignmentDetails;
There are multiple ReferralTherapists for each referral. I need all the ReferralTherapists for each referral to be concatenated into one field. Essentially what I want to do is a GROUP_CONCAT using LINQ.
I know this is probably a duplicate, but none of the previous questions handles anything as complicated as this. Trying to add GroupBy always seems to create an error no matter where I place it.
Start by not joining other referrals as t2 when constructing your flat list, and adding therapist's name to the anonymous type:
var flatListAssignmentDetails =
(from t1 in _unitOfWork.ReferralDetailsRepository.Get()
.Where(m => (m.ChartStatusID == (int)Utility.ReferralChartStatus.NotStaffed
|| m.ChartStatusID == (int)Utility.ReferralChartStatus.Partially_Staffed
|| m.ChartStatusID == (int)Utility.ReferralChartStatus.Restaff)
&& !m.IsDeleted)
join t2 in _unitOfWork.ReferralRepository.Get() on t1.ReferralId equals t2.ReferralId
join t3 in _unitOfWork.PatientRepository.Get() on t2.PatientId equals t3.PatientId
join t4 in _unitOfWork.ClientRepository.Get() on t2.ClientId equals t4.ClientID
join t5 in _unitOfWork.DisciplineRepository.Get() on t1.DesciplineID equals t5.DesciplineID
join t6 in _unitOfWork.UserRepository.Get() on t2.CreatedBy equals t6.UserID
join t7 in _unitOfWork.PersonRepository.Get() on t6.PersonID equals t7.PersonID
select new {
t1.ReferralId,
t4.ClientName,
PatientName = t3.LastName + "," + t3.FirstName,
t2.RefferalDate,
t1.DisciplineID,
t1.ReferralDetailsId,
t2.PatientId,
t4.ClientID,
DiscName = t5.DesciplineType,
t1.IsRejected,
CreatedBy = t7.LastName + "," + t7.FirstName,
ChartstatusId = t1.ChartStatusID.Value,
TherapistName = p.LastName + "," + p.FirstName
}).ToList();
Now you can group your list, and concatenate therapist names:
var listAssignmentDetails = flatListAssignmentDetails
.GroupBy(r => r.ReferralId)
.Select(g => new ReferralTempModel {
ReferralId = g.First().ReferralId,
ClientName = g.First().ClientName,
PatientName = g.First().PatientName,
RefferalDate = g.First().RefferalDate,
DisciplineID = g.First().DisciplineID,
ReferralDetailsId = g.First().ReferralDetailsId,
PatientId = g.First().PatientId,
ClientID = g.First().ClientID,
DiscName = g.First().DiscName,
IsRejected = g.First()..IsRejected,
CreatedBy = g.First().CreatedBy,
ChartstatusId = g.First().ChartStatusID,
TherapistNames = string.Join(", ", g.Select(r => r.TherapistName))
}).ToList();
One thing to note here is that all fields that are tied to all referrals in the group are obtained through g.First() construct. The field with "group concatenation" is produced using string.Join method on a projection of TherapistName from the group.

How create it in Laravel Query builder

SELECT e.match_id, e.team_id
FROM matches
LEFT JOIN match_events e
ON e.match_id = matches.id AND e.match_event_type_id = 1
Try this,
$result = DB::table('matches as M')
->leftjoin('match_events as E','E.match_id','=','M.id')
->where('E.match_event_type_id',1)
->select(['E.match_id','E.team_id'])
->get();

How to load products from a specific category based on special price availability?

I have following code
$promoCatId = (int)Mage::getStoreConfig('promoprodsec/promoprodgroup/promocategoryid');
$products = Mage::getModel('catalog/category')->setStoreId($store)->load($promoCatId)
->getProductCollection();
$allProductsInPromoCategory = $products->getAllIds();
It gives me all the products of $promoCatId category.
Now I want to get all the products which are not having special price or the special price date range has expired from all the products of $allProductsInPromoCategory
How can I accomplish this without using foreach loop and again loading every product collection again?
foreach ($allProductsInPromoCategory as $promoprod) {
Mage:getModel('catalog/product')->load( $promoprod);
//do validation for the special price criteria
}
Once you state ->getProductCollection() on your category, you end up with a object of type Mage_Catalog_Model_Resource_Product_Collection, which is basically a product collection like all the other.
Since this collection is an EAV collection, you can filter it with the help of the function addAttributeToFilter
And since you actually want an OR (where special price is null or special to date <= now()), you want your two conditions to be in the same addAttributeToFilter
So I would say you can achieve this by doing :
$promoCatId = (int)Mage::getStoreConfig('promoprodsec/promoprodgroup/promocategoryid');
$products = Mage::getModel('catalog/category')
->setStoreId($store)
->load(promoCatId)
->getProductCollection()
->addAttributeToFilter(
array(
array('attribute' => 'special_price', 'null' => true),
array('attribute' => 'special_from_date', 'lt' => Mage::getModel('core/date')->date(Varien_Date::DATETIME_PHP_FORMAT))
)
);
$allProductsInPromoCategory = $products->getAllIds();
echo $products->getSelect();
Useful to know :
I am actually using Mage::getModel('core/date')->date(Varien_Date::DATETIME_PHP_FORMAT) to get the current date relative to the configured locale timezone of the store
echo $products->getSelect(); on a collection will display you the query done by Magento, really useful to actually see if the where is what you really want it to be. In my case it displays :
SELECT `e`.*, `cat_index`.`position` AS `cat_index_position`,
`at_special_price`.`value` AS `special_price`,
IF(at_special_from_date.value_id > 0, at_special_from_date.value,
at_special_from_date_default.value) AS `special_from_date` FROM
`catalog_product_entity` AS `e` INNER JOIN
`catalog_category_product_index` AS `cat_index` ON
cat_index.product_id=e.entity_id AND cat_index.store_id=1 AND
cat_index.category_id = '15' INNER JOIN
`catalog_product_entity_decimal` AS `at_special_price` ON
(`at_special_price`.`entity_id` = `e`.`entity_id`) AND
(`at_special_price`.`attribute_id` = '76') AND
(`at_special_price`.`store_id` = 0) INNER JOIN
`catalog_product_entity_datetime` AS
`at_special_from_date_default` ON
(`at_special_from_date_default`.`entity_id` = `e`.`entity_id`)
AND (`at_special_from_date_default`.`attribute_id` = '77') AND
`at_special_from_date_default`.`store_id` = 0 LEFT JOIN
`catalog_product_entity_datetime` AS `at_special_from_date` ON
(`at_special_from_date`.`entity_id` = `e`.`entity_id`) AND
(`at_special_from_date`.`attribute_id` = '77') AND
(`at_special_from_date`.`store_id` = 1) WHERE
((at_special_price.value IS NULL) OR (IF(at_special_from_date.value_id
> 0, at_special_from_date.value, at_special_from_date_default.value) < '2016-01-08 22:05:14'))

How to speed this query up?

I'm using yii framework to create a website takes care of poems and words and stuff...
the problem is that the database has more than 250,000 record of messages and more than 500,000 records of keywords and relationships :S
what I'm trying to say that I want to make an optimal query to get all related messages of a specific message depending on key-tags..
what I did so far is caching the query, but it's still slow when opening it for the first time and that's a big problem!
here is my code:
public function getRelatedMessages()
{
$id = $this->id;
$dependency = "select `messages`.id,count(id) as tag_count from messages left join `messages_tags` on `messages`.`id` = `messages_tags`.mid
where `messages_tags`.`tagid` in (select `tags`.`id` from tags left join `messages_tags` on tags.id = `messages_tags`.tagid
where `messages_tags`.`mid` = {$id}) and id <> {$id} group by id order by tag_count desc";
$dependency = Messages::model()->cache(900)->findAllBySql($dependency);
foreach ($dependency as $dependency) {
$dependency1[] = $dependency['id'];
}
$dependency = implode(", ", $dependency1);
$sql = "select * from messages where id in ({$dependency}) limit 4";
$relateds = Messages::model()->findAllBySql($sql);
$db = array();
foreach($relateds as $related) {
$db[] = $related;
}
if(!$relateds || count($db)<4) {
$limit = 4-count($db);
$sql = "select `messages`.id, `messages`.url_key, `messages`.photo_url, `messages`.message from messages order by rand(), likes desc, comments desc, impressions desc, reported asc limit {$limit};";
$relateds = Messages::model()->cache(900)->findAllBySql($sql);
foreach($relateds as $related) {
$db[] = $related;
}
}
return $db;
}
the code above selects only 4 records from the related messages after filtering them and ordering them and stuff.. the problem is with "order by" but I need it :S
sorry if that was too long..
thank you :)
You could improve the first query by not using findAllBySql() and instantiating all the ActiveRecord classes. You don't need them, so use plain sql query like this (query stays the same but code around has changed):
// ...
$dependency = $this->dbConnection->createCommand("
select `messages`.id, count(id) as tag_count
from messages left join `messages_tags` on `messages`.`id` = `messages_tags`.mid
where
`messages_tags`.`tagid` in
(select `tags`.`id` from tags left join `messages_tags` on tags.id = `messages_tags`.tagid where `messages_tags`.`mid` = {$id})
and id <> {$id}
group by id order by tag_count desc")->queryColumn();
$dependency = implode(", ", $dependency);
$sql = "select * from messages where id in ({$dependency}) limit 4";
$relateds = Messages::model()->findAllBySql($sql);
// ...

Symfony Doctrine_Query DELETE with INNER JOIN

I am using symfony+doctrine, and I want to perform a delete query with a join. See below for my code I am currently using that works fine.
$sql = 'DELETE a
FROM a
INNER JOIN b ON a.b_id = b.id
WHERE b.c_id = :c_id';
$pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
$stmt = $pdo->prepare($sql);
$params = array('c_id' => $c_id);
$stmt->execute($params);
Anyone know how I can do this using:
Doctrine_Core::getTable('a')
Or
Doctrine_Query::create()->delete()->from('a')
I have had no luck with either.
I just don't really want to use raw SQL in my app.
Something like this should do it
Doctrine_Query::create()
->delete('a a')
->innerJoin('a.b b')
->where('b.c_id = ?', $c_id)
->execute()

Resources