How do sub-query in JOIN Codeigniter? - php

I tried to do sub-query SELECT in LEFT JOIN with an Active Records CI, but it gives an error:
near 'b.MedicalFacilitiesIdUser FROM medicalfacilities AS b WHERE b.MedicalFacilitiesI'
How as look, the query was distorted: b.MedicalFacilitiesI
Query is:
$this->db->join('stocks AS stn', 'stn.stocksIdMF =
(SELECT b.MedicalFacilitiesIdUser FROM medicalfacilities AS b
WHERE b.MedicalFacilitiesIdUser = stn.stocksIdMF AND stn.stocksEndDate >= UNIX_TIMESTAMP()
ORDER BY stn.stocksId DESC LIMIT 1)', 'LEFT');
Now full query is:
$this->db->select("MedicalFacilitiesName, MedicalFacilitiesAdres, MedicalFacilitiesDescription,
MedicalFacilitiesView, medicalfacilities.country, medicalfacilities.city, MedicalFacilitiesPhoto,
MedicalFacilitiesIdUser, idMedicalFacilities, id_specialization, id_MF, idUsers, UsersTypeAccount,
COUNT(commentstomedicalfacilities.idCommentsToMedicalFacilities) AS CNT,
COUNT(DISTINCT(stocks.stocksId)) AS count_stocks,
COUNT( su.idSubscrubeToUsers ) AS SBS,
coalesce(ROUND((SUM(ev.evaluationinstitutionEvalTotal) / SUM(ev.evaluationinstitutionEvalTotalRate))), 0) AS rate,
stocks.stocksName, stocks.stocksId, stocks.stocksEndDate, stocks.stocksStartDate,
typesmedicalfacilities.name AS nameType", FALSE);
$this->db->from('medicalfacilities');
$this->db->join('users', 'users.idUsers = medicalfacilities.MedicalFacilitiesIdUser');
$this->db->join('medicalfacilities_directions', 'medicalfacilities_directions.id_MF = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
$this->db->join('subscrubetousers su', 'su.SubscrubeToUsersIdNote = medicalfacilities.MedicalFacilitiesIdUser AND su.SubscrubeToUsersType = 9', 'LEFT');
$this->db->join('thematicspecialization', 'thematicspecialization.idSpecialization = medicalfacilities_directions.id_specialization', 'LEFT');
$this->db->join('evaluationinstitution ev', 'ev.evaluationinstitutionIdInst = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
$this->db->join('stocks', 'stocks.stocksIdMF = medicalfacilities.MedicalFacilitiesIdUser AND stocks.stocksEndDate >= UNIX_TIMESTAMP()', 'LEFT');
$this->db->join('commentstomedicalfacilities', 'commentstomedicalfacilities.CommentsToMedicalFacilitiesIdMedical = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
$this->db->join('medicalfacilities_type', 'medicalfacilities_type.idMF = medicalfacilities.MedicalFacilitiesIdUser');
$this->db->join('typesmedicalfacilities', 'typesmedicalfacilities.type = medicalfacilities_type.type');
$this->db->join('stocks AS stn', 'stn.stocksIdMF = (SELECT b.MedicalFacilitiesIdUser FROM medicalfacilities AS b WHERE b.MedicalFacilitiesIdUser = stn.stocksIdMF AND stn.stocksEndDate >= UNIX_TIMESTAMP()
ORDER BY stn.stocksId DESC LIMIT 1)', 'LEFT');

Related

How do I call the BETWEEN function in php?

I am trying to filter by date and status, in mysql the query is fine, but when implementing php it does not work for me.
My Consult Sql
SELECT `loan_items`.*
FROM `loan_items`
WHERE `date` BETWEEN '2023-03-10' AND '2023-03-10' AND `status` = 1;
Code Php
$date = date("y-d-m");
$this->db->select("li.id, c.dni, concat(c.first_name,' ',c.last_name) AS name_cst, l.id AS loan_id, li.pay_date, li.num_quota, li.fee_amount");
$this->db->from('loan_items li');
$this->db->join('loans l', 'l.id = li.loan_id', 'left');
$this->db->join('customers c', 'c.id = l.customer_id', 'left');
$this->db->where(['li.status' => 1, 'li.date' => "BETWEEN :$date AND :$date"]);
$this->db->order_by('li.pay_date', 'desc');
This way it works but it doesn't show me the date
$this->db->select("li.id, c.dni, concat(c.first_name,' ',c.last_name) AS name_cst, l.id AS loan_id, li.pay_date, li.num_quota, li.fee_amount");
$this->db->from('loan_items li');
$this->db->join('loans l', 'l.id = li.loan_id', 'left');
$this->db->join('customers c', 'c.id = l.customer_id', 'left');
$this->db->where('li.status', 1);
$this->db->order_by('li.pay_date', 'desc');

Doctrine - How do you use a subquery column (in the SELECT clause and having condition)

Hello i am trying to rewrite ZF query builder into doctrine ORM.
Here IS mine old Zend framework query.
$dependent = new Zend_Db_Expr('if(br.billing_rate = \'dependent\',(SELECT COUNT(*) FROM childcare_billing_rule_price AS p WHERE p.id < brp.id AND p.childcare_billing_rule_id = brp.childcare_billing_rule_id),0)');
$select = $this
->select()->setIntegrityCheck(false)
->from(array('brg' => 'childcare_billing_rule_group'), array())
->joinInner(array('br' => 'childcare_billing_rule'), 'br.id = brg.billing_rule_id', array('*', 'dependent' => $dependent))
->join(array('brp' => 'childcare_billing_rule_price'), 'br.id = brp.childcare_billing_rule_id', array('age_from', 'age_to', 'default_rate' => 'rate'))
->where('is_default != 1')
->where('br.billing_type in (\'' . implode('\',\'', array(self::BILLING_TYPE_PER_DAY, self::BILLING_TYPE_PER_HOUR, self::BILLING_TYPE_PER_UNLIMITED, self::BILLING_TYPE_PER_RESERVATION)) . '\')')
->where('brg.group_id IN (?)', $groupId)
->group('brp.id')
->having('dependent <= ?', $dependentLevel)
->order('dependent desc')
->order('brp.rate');
And here it is SQL row value
SELECT `br`.*,
if (br.billing_rate = 'dependent',
(SELECT COUNT(*) FROM childcare_billing_rule_price AS p WHERE p.id < brp.id AND p.childcare_billing_rule_id = brp.childcare_billing_rule_id),
0) AS `dependent`,
`brp`.`age_from`,
`brp`.`age_to`,
`brp`.`rate` AS `default_rate`
FROM `childcare_billing_rule_group` AS `brg`
INNER JOIN `childcare_billing_rule` AS `br` ON br.id = brg.billing_rule_id
INNER JOIN `childcare_billing_rule_price` AS `brp` ON br.id = brp.childcare_billing_rule_id
WHERE (is_default != 1)
AND (br.billing_type in ('Per Day','Per Hour','Unlimited','Per Reservation'))
AND (brg.group_id IN (103))
AND ((brp.age_from = 0 AND brp.age_to = 0) || 3.1666666666667
BETWEEN brp.age_from AND brp.age_to)
GROUP BY `brp`.`id` HAVING (dependent <= '0')
ORDER BY `dependentw` desc,
`brp`.`rate` ASC
I am not sure how to implement this sub query
new Zend_Db_Expr('if(br.billing_rate = \'dependent\',(SELECT COUNT(*) FROM childcare_billing_rule_price AS p WHERE p.id < brp.id AND p.childcare_billing_rule_id = brp.childcare_billing_rule_id),0)');
My code so far
$subQuery = $subQueryBuilder
->select('if (br.billing_rate = 'dependent',
(SELECT COUNT(*) FROM childcare_billing_rule_price AS p WHERE p.id < brp.id AND p.childcare_billing_rule_id = brp.childcare_billing_rule_id)')
->getSQL();
$queryBuilder->select($alias)
->addSelect($subQuery)
->innerJoin(ChildcareBillingRule::class, 'br', Join::WITH, 'br.id = childcare_billing_rule_group.childcareBillingRule')
->innerJoin(ChildcareBillingRulePrice::class, 'brp', Join::WITH, 'br.id = brp.childcareBillingRule')
->where("br.billingType in (:billingTypes)")
->andWhere( 'br.isDefault != :isDefault')
->andWhere( 'childcare_billing_rule_group.groupId in (:groupId)')
->setParameter('groupId', [103])
->setParameter('isDefault', 1)
->setParameter('billingTypes', ['Per Hour', 'Per Reservation', 'Per Day', 'Unlimited'])
->having('dependent <= ?', $dependentLevel')
->groupBy('brp.id')
->orderBy('brp.rate') ;
->getQuery()->getSingleResult();
so i am trying to add sub query with addSelect but not sure is this the right way? Any Help or idea is appreciated? Tnx
in short instead of ->getSQL() you should use ->getDQL().
Yours code will be like:
$dql = $this->createQueryBuilder()
->select('count(id)')
->from({Class::FQDN}, {ALIAS})
->getDQL();
$result = $this->createQueryBuilder()
->select({SECOND_ALIAS})
->from({SecondClass::FQDN}, {SECOND_ALIAS})
->where((new \Expr())->gt('{SECOND_ALIAS}.cnt', $dql))
->getQuery()
->getResult();

Active Record is not displaying correct query

Can anybody tell me why im not able to display the following query using active record in codeigniter. I suppose there is something wrong with TIMEDIFF in my select statement as theres no space between TOTAL and FROM
This is my active record query
$this->db->select('s.id, s.person_id, p.first_name, p.last_name, sch.id, sch.start_date, sch.start_hour, sch.end_hour, TIMEDIFF(sch.end_hour, sch.start_hour) AS total');
$this->db->join('staff s', 'sch.staff_id = s.id', 'left');
$this->db->join('persons p', 's.person_id = p.id', 'left');
$this->db->where('sch.start_date >=', $start);
$this->db->where('sch.start_date <=', $end);
$this->db->limit(10);
$query = $this->db->get('work_schedule sch');
And this is how is printed out
SELECT `s`.`id`,
`s`.`person_id`,
`p`.`first_name`,
`p`.`last_name`,
`sch`.`id`,
`sch`.`start_date`,
`sch`.`start_hour`,
`sch`.`end_hour`,
TIMEDIFF(sch.end_hour,`sch`.`start_hour)` AS totalFROM (`work_schedule` sch)
LEFT JOIN `staff` s ON `sch`.`staff_id` = `s`.`id`
LEFT JOIN `persons` p ON `s`.`person_id` = `p`.`id`
WHERE `sch`.`start_date` >= '2014-02-19'
AND `sch`.`start_date` <= '2014-02-20'LIMIT 10
You can try it.
$query = $this->db->select('s.id, s.person_id, p.first_name, p.last_name, sch.id, sch.start_date, sch.start_hour, sch.end_hour, TIMEDIFF(sch.end_hour, sch.start_hour) AS total', FALSE)
->from('work_schedule sch')
->join('staff s', 'sch.staff_id = s.id', 'left')
->join('persons p', 's.person_id = p.id', 'left')
->where('sch.start_date >=', $start)
->where('sch.start_date <=', $end)
->limit(10)
->get();
$result = $query->result();

how to use or_where and where in codeigniter

I am facing a problem when using active record or_where
how i do or only for one particular field i.e meeting_status
$this->db->_protect_identifiers=false;
$this->db->select("g.category_id,f.doc_type_id,g.category_name,f.doc_type_name,c.meeting_name_id, c.meeting_name as mn, d.meeting_type_id, d.meeting_type_name, e.venue_id, e.venue_name, u.*, (select count(*) from tbl_meeting_decisions where meeting_id=u.meeting_id and record_status= 'ACTIVE') as `meeting_decision`, (select count(*) from tbl_meeting_actions where meeting_id=u.meeting_id and record_status= 'ACTIVE') as `meeting_action`, (select count(*) from tbl_meeting_actions where meeting_id=u.meeting_id and action_status='OPEN' and record_status= 'ACTIVE') as `meeting_close_action`");
$this->db->from('tbl_meeting_plans u');
$this->db->join('tbl_meeting_names c', 'c.meeting_name_id = u.meeting_name');
$this->db->join('tbl_meeting_types d', 'd.meeting_type_id = u.meeting_mode_id');
$this->db->join('tbl_meeting_venue e', 'e.venue_id = u.venue_id ');
$this->db->join('tbl_document_types f', 'f.doc_type_id = u.meeting_type_id ');
$this->db->join('tbl_categories g', 'g.category_id = u.meeting_category_id ');
$this->db->where(array('u.meeting_type_id'=>$str2,'u.meeting_category_id'=>$str1,'u.meeting_status'=>'Planning','u.record_status'=>'ACTIVE' ));
$this->db->or_where(array('u.meesting_status'=>'Meeting Updated' ));
$where = "(u.meeting_status='Planning' or u.meeting_status='Meeting
Updated') ";
$this->db->where($where);
Before this use the normal where clause

How to join the same table twice and assign table aliases in Codeigniter?

I'm trying to make a mail system in Codeigniter with the PyroCms.
In my mail table, I have a "recipent" row and a "sender" row which contains the user id of the sender and recipient. To retrieve usernames from the ids, I'm trying to join the table together, but it simply returns me this error:
Error Number: 1066
Not unique table/alias: 'default_users'
SELECT `default_mailsystem`.*, `default_users`.`username` AS modtager, `default_users`.`username` as afsender
FROM (`default_mailsystem`)
LEFT JOIN `default_users` ON `default_mailsystem`.`recipent` = `default_modtager`.`id`
LEFT JOIN `default_users` ON `default_mailsystem`.`sender` = `default_afsender`.`id`
ORDER BY `id` DESC
Filename: /hsphere/local/home/brightmedia/reuseable.dk/modules/mail/models/mail_m.php
Line Number: 13
My code is as follows:
$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
->join('users', 'mailsystem.recipent = modtager.id', 'left')
->join('users', 'mailsystem.sender = afsender.id', 'left');
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
The funny thing is, that if I remove the last "join" operation and leave it to only join the recipient of the mail it all works out well.
This is very simple
$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND mailsystem.sender = afsender.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
Have you tried forcing an alias in the join function (the "AS" operator won't work in the select clause as you have it...)?
<?php
$this->db->select('mailsystem.*, modtager.username AS modtager_name, afsender.username as afsender_name')
->join('`users` `modtager`', 'mailsystem.recipent = modtager.id', 'left')
->join('`users` `afsender`', 'mailsystem.sender = afsender.id', 'left');
$this->db->order_by('mailsystem.id', 'DESC');
return $this->db->get('mailsystem')->result();
Use alias like this -
$this->db->select('mailsystem.*, users_table_a.username AS modtager, users_table_b.username as afsender')
$this->db->join('users users_table_a', 'mailsystem.recipent = users_table_a.id', 'left');
$this->db->join('users users_table_b', 'mailsystem.sender = users_table_b.id', 'left');
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
you can use this :
$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND mailsystem.sender = afsender.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
*If you are using any db prefix use this *
$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND '.$this->db->dbprefix('mailsystem').'.sender = '.$this->db->dbprefix('afsender').'.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
Its very easy to get data from single table
$this->db->select('a.*,b.fname AS cname,c.fname as uname');
$this->db->from('tbl_menus a');
$this->db->join('tbl_admin_login b', 'b.id = a.create_by', 'left');
$this->db->join('tbl_admin_login c', 'c.id = a.update_by', 'left');
$this->db->order_by('a.id', 'desc');
return $this->db->get()->result_array();
At the time of this thread, i figured that the codeigniter call missed out the possibility to do AS inside of a join, Therefor this solved the issue:
$sql = "
SELECT default_mailsystem.*,
recipent.first_name AS modtager,
sender.first_name AS afsender
FROM default_mailsystem
LEFT JOIN default_profiles AS recipent ON recipent.id = default_mailsystem.id
LEFT JOIN default_profiles AS sender ON sender.id = default_mailsystem.id
";
return $this->db->query($sql)->result();
Your can try this
Core PHP
SELECT `custome_module`.`id`, `custome_module`.`name`, min(l1.nmark_completed) as call_waiter, min(l2.nmark_completed) as bill, min(l3.nmark_completed) as tray, min(l4.nmark_completed) as ordera
FROM `custome_module`
LEFT JOIN `restaurant_logs` as `l1` ON `custome_module`.`id` = `l1`.`nmodule_id` AND `l1`.`ntype` = 1
LEFT JOIN `restaurant_logs` as `l2` ON `custome_module`.`id` = `l2`.`nmodule_id` AND `l2`.`ntype` = 2
LEFT JOIN `restaurant_logs` as `l3` ON `custome_module`.`id` = `l3`.`nmodule_id` AND `l3`.`ntype` = 6
LEFT JOIN `restaurant_logs` as `l4` ON `custome_module`.`id` = `l4`.`nmodule_id` AND `l4`.`ntype` = 5
WHERE `custome_module`.`nbranch_id` = '142'
GROUP BY `custome_module`.`id`
and also in Codeigniter
$this->db->select('custome_module.id, custome_module.name, min(l1.nmark_completed) as call_waiter, min(l2.nmark_completed) as bill,min(l3.nmark_completed) as tray,min(l4.nmark_completed) as ordera');
$this->db->from("custome_module");
$this->db->join('restaurant_logs as l1', 'custome_module.id = l1.nmodule_id AND l1.ntype = 1', 'left');
$this->db->join('restaurant_logs as l2', 'custome_module.id = l2.nmodule_id AND l2.ntype = 2', 'left');
$this->db->join('restaurant_logs as l3', 'custome_module.id = l3.nmodule_id AND l3.ntype = 6', 'left');
$this->db->join('restaurant_logs as l4', 'custome_module.id = l4.nmodule_id AND l4.ntype = 5', 'left');
$this->db->where('custome_module.nbranch_id', $this->data['user_session']['nid']);
$this->db->get();

Categories