i have this db function in f3 framework
public function sumOfAmount($startdate, $enddate) {
$this->amount = 'price*quantity';
$this->sumamount = 'SUM(price*quantity)';
$this->load(array('createon > ? AND createon < ?', $startdate, $enddate));
//return $this->query;
return $this->cast();
}
it seem that sumamount is not correct , from the f3 log i have this query executed
SELECT `idproduct`,`idtransaction`,`idline`,`name`,`code`,`price`,`quantity`,`createon`,(price * quantity) AS `amount`,(SUM(price * quantity)) AS `sumamount` FROM `qrysales`
but if i run that query in phpmyadmin result is ok
Any idea??
it seems that i forgot group by clause
public function sumOfAmount($startdate, $enddate) {
$this->amount = 'price*quantity';
$this->sumamount = 'SUM(price*quantity)';
$this->load(array('createon > ? AND createon < ?', $startdate, $enddate,'group' => 'idline'));
//return $this->query;
return $this->cast();
}
Related
I am making some DB query via repository (ORM), I want to get a list of objects.
What's my problem?
I have two methods in the repository: getList() to get a list and getCount() to get the number of total records for information.
getList() gives me 5 records, and getCount() gives the number 9.
public function getList($criteria, $page, $limit, $orderBy, $joins = [])
{
$qb = $this->createQueryBuilder('a')->select('a');
if(!empty($joins)) {
$qb = $this->setCriteriaByJoins($qb, $joins);
}
$qb = $this->setCriteriaToQuery($qb, $criteria);
foreach($orderBy as $order) {
$qb->addOrderBy('a.' . $order[0], $order[1]);
}
if($page && $limit) {
$offset = ($page - 1) * $limit;
$qb->setFirstResult($offset)
->setMaxResults($limit);
}
$result = $qb->getQuery()->getResult();
return $result;
}
public function getCount($criteria = [], $joins = []) {
try {
$qb = $this->createQueryBuilder('a')->select('count(a.id)');
if(!empty($joins)) {
$qb = $this->setCriteriaByJoins($qb, $joins);
}
$qb = $this->setCriteriaToQuery($qb, $criteria);
$result = $qb->getQuery()->getSingleScalarResult();
} catch(\Exception $e) {
$result = 0;
}
return $result;
}
In debugging, I see that the getList() request was built like this:
SELECT r0 _. * FROM film r0_ LEFT JOIN person_film r1_ ON (r0_.id = r1_.film_id) WHERE r1_.person_id IN (45793) AND r0_.status = 1 ORDER BY r0_.`release` DESC, r0_.id DESC LIMIT 48
and getCount()
SELECT count (r0_.id) AS sclr_0 FROM film r0_ LEFT JOIN person_film r1_ ON (r0_.id = r1_.film_id) WHERE r1_.person_id IN (45793) AND r0_.status = 1
Requesting getList() from the repository gives me 5 records. However, if I directly ask the database with this query (without ORM), then I will get 9 records. Of these 9 records, 4 are duplicated due to the fact that the person_film table can contain more than one record with the same film_id and person_id (these records differ in other fields). I found that /vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:hydrateRowData() removes duplicates.
How to do to make the ORM in the getList() request return all 9 records, even if they are duplicates?
And vice versa. How to do to the getCount() to return 5.
it seems like this is the answer to the second question
public function getCount($criteria = [], $joins = [], $distinct = false) {
try {
$sq = ($distinct) ? 'count(distinct(a.id))' : 'count(a.id)';
$qb = $this->createQueryBuilder('a')->select($sq);
if(!empty($joins)) {
$qb = $this->setCriteriaByJoins($qb, $joins);
}
$qb = $this->setCriteriaToQuery($qb, $criteria);
$result = $qb->getQuery()->getSingleScalarResult();
} catch(\Exception $e) {
$result = 0;
}
return $result;
}
I'm working on a Symfony project that makes use of a
Repository file in which I have declared and created an instance of a query builder
(repository1)
$mk = $this->createQueryBuilder('up');
$later = date("Y-m-d", strtotime("-3 months"));
$today = date("Y-m-d");
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
automatically this generates data for my page between the above dates.
Now I want to create a form where I can make a search between two dates.
with the intention of passing the posted data from this form to my controller into my method below
My controller below (controller1)
protected function getData(EntityManagerInterface $entityManager,Request $request) {
// this code to get data from repository
$entityManager->getRepository(repository1::class)->getName()
// receive posted data
$date1 = $request->get('date');
$date2 = $request->get('date');
// now how to pass data to my repository1
}
Please how do I edit what I have to post data from within my controller to my (repository1)
so then it would be
$mk = $this->createQueryBuilder('up');
$later = $date1;
$today = $date2;
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
is this even possible, or im over thinking it?
RepositoryClass
public function getByStartEndDate(DateTimeInterface $start, DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}
Controller Class
private function getData(Request $request, RepositoryClass $repo)
{
// May need to convert these to DateTime objects
$start = $request->get('start');
$end = $request->get('end');
$records = $repo->getByStartEndDate($start, $end);
// do what you want with the records here
}
You can give the dates as parameters to your method.
Controller Class:
protected function getData(EntityManagerInterface $entityManager,Request $request) {
$start = $request->get('start') ? new \DateTime($request->get('start')) : null;
$end = $request->get('end') ? new \DateTime($request->get('end')) : null;
$result = $entityManager->getRepository(Entity::class)->getName($start, $end);
// do with result as desired
}
Repository Class:
public function getName(\DateTimeInterface $start, \DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}
I have a method to return results from db from startDate to endDate passing in like parameters in postman.
Everything seems to be working fine but it returns all results from database.
I think that problem could be with parameters..
public function getInvoices($fromDate = null, $toDate = null)
{
$query = $this->entityManager->getRepository(Invoice::class)
->createQueryBuilder('ur')
->select('ur')
->orderBy('ur.invoiceDate', 'ASC');
if($fromDate) {
$query
->andWhere('t.invoiceDate >= :startDate')
->setParameter('startDate', new \DateTime($fromDate));
}
if($toDate) {
$query
->andWhere('t.invoiceDate <= :endDate')
->setParameter('endDate', new \DateTime($toDate));
}
return $query->getQuery()->getResult();
}
And I am calling this method in my controller like:
$data = [];
$responseData = $this->invoiceService->getInvoices(
#$this->data['startDate'],
#$this->data['endDate']
);
I pass this two parameters via postman and it returns all results:
Here is an image: here
This is the function I am using in my model
public function user_birthday() {
$this->db->select('birth_day')
->from('informations')
->where(DATE_FORMAT(FROM_UNIXTIME('birth_day'), '%m-%d') = DATE_FORMAT(NOW(), '%m-%d'));
$q = $this->db->get();
return $q->result();
}
function in controller like $this->data['user'] = $this->users_m->user_birthday(); that way
and code in the view is
if (!empty($user)):
echo $user;
else:
echo "No dob found";
endif;
This is one of those circumstances where Query Builder is more trouble that it is worth. Try this
$q= $this->db->query("SELECT birth_day FROM informations WHERE DATE_FORMAT(birth_day, '%m-%d') = DATE_FORMAT(NOW(), '%m-%d')");
//return empty array if not records found
return $q->num_rows() > 0 ? $q->result() : [];
If you really, really, really want to use Query Builder then this
$q = $this->db
->select('birth_day')
->where("DATE_FORMAT(birth_day, '%m-%d')=", "DATE_FORMAT(NOW(), '%m-%d')", FALSE)
->get('informations');
return $q->num_rows() > 0 ? $q->result() : [];
In the code below,I'm getting an empty array for the third if-else statement. What I'm trying is that get a range of date from user and showing the data from the table accordingly. My first if-else statement is returning desired results but the second one is returning empty array.
Controller:
public function bookings()
{
if($this->userlib->isLoggedIn())
{
if($this->userlib->isAdmin())
{
$this->load->view('admin_search_booking');
$date_posted_from = $this->input->post('date_posted_from');
$date_posted_till = $this->input->post('date_posted_till');
$date_posted_on = $this->input->post('date_posted_on');
if(is_null($date_posted_from) && is_null($date_posted_till) && is_null($date_posted_on))
{
$total_trails = $this->admin_panel_model->total_trail();
var_dump($total_trails);
}
elseif(!is_null($date_posted_on))
{
$total_trails = $this->admin_panel_model->filter_on_date($date_posted_on);
var_dump($total_trails);
}
elseif(!is_null($date_posted_from) && !is_null($date_posted_till))
{
$total_trails = $this->admin_panel_model->filter_by_date($date_posted_from, $date_posted_till);
var_dump($total_trails);
}
}
}
else
{
echo "User not Logged In";
}
}
Model filter_by_date :-
public function filter_by_date($date_posted_from, $date_posted_till)
{
$query = $this->db->select('*')
->where('date >=', $date_posted_from)
->where('date <=', $date_posted_till)
->get($this->search);
return $query->result();
}
isLoggedIn :-
public function isLoggedIn()
{
if($this->ci->session->email)
return true;
else
return false;
}
Change your model function like this
public function filter_by_date($date_posted_from="", $date_posted_till="")
{
$query = $this->db->select('*');
if($date_posted_from)
$this->db->where('date >=', $date_posted_from);
if($date_posted_till)
$this->db->where('date <=', $date_posted_till);
$this->db->get($this->search);
return $query->result();
}
//This may help you put your table name in your select statement and update where clause
public function filter_by_date($date_posted_from, $date_posted_till){
$date_posted_from='2015-10-10';
$date_posted_till='2015-10-16';
$query = $this->db->select('*')->from('Your_Table_Name')
->where("date >= '".$date_posted_from."'")
->where("date <= '".$date_posted_till."'")
->get($this->search);
return $query->result();
}
Use $this->db->last_query(); after filter_by_date() and check what query is actually being executed. And also make sure there are records exists in the date range you are searching for.
Or simply use straight forward query,
$Q = $this->db->query("select * from table_name where date >='".$date_posted_from."' and date <='".$date_posted_to."'");
return $Q->result_array();