How to select all values with latest dates Laravel 5.8 - date

I am trying to get all of the rows with the latest dates
I want to get the rows 3 and 4 only
When I use this eloquent query:
$items = Purchase::whereYear('created_at', '=', $year)
->whereMonth('created_at', '=', $month)
->where('created_at', Purchase::max('created_at'))
->get();
return $items;
Yet this is what I get:
[{"id":4,"itemid":1,"price":"1.60","quantity":4,"created_at":"2019-09-14 08:39:31","updated_at":"2019-09-14 08:39:31"}]

You must be use ->whereDate() function
$lastDate = Purchase::max('created_at')->format('Y-m-d');
$items = Purchase::whereDate('created_at', $lastDate)->get();
Edit:
$lastDate = Carbon::parse(Purchase::max('created_at'))->format('Y-m-d');
$items = Purchase::whereDate('created_at', $lastDate)->get();

Related

Convert Join to sub Query

I have a join and i want to convert it to subQuery. Can someone please help me to do the same.
Here is the join with db table i have:
$jobId = 12;
$customerId = 15;
DB::table('user_access_customer_job')
->join('user_access_customer_job as parent_jobs', 'user_access_customer_job.parent_job_id', '=', 'parent_jobs.job_id')
->where('parent_jobs.job_id', '<>', $jobId)
->where('parent_jobs.customer_id', $customerId)
->where('user_access_customer_job.job_id', '<>', $jobId)
->whereRaw('parent_jobs.user_id <=> user_access_customer_job.user_id')
->whereRaw('parent_jobs.type = user_access_customer_job.type')
->select('parent_jobs.id')
->lists('id');

PostgreSQL error witn Laravel

I'm trying to make a request and I have an error when I'm using LIKE on the created_at field.
I'm using Laravel 5.3 with Eloquent (ORM).
$date = Carbon::now();
foreach ($hours as $hour) {
$chart[$hour]['hour'] = $hour;
$chart[$hour]['allowed'] = VisitsAllowed::where('created_at', 'LIKE', Carbon::parse($date)->format('Y-m-d %'))->count();
$chart[$hour]['denied'] = VisitsDenied::where('created_at', 'LIKE', Carbon::parse($date)->format('Y-m-d %'))->count();
}
Error :
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: timestamp without time zone ~~* unknown
LINE 1: ... aggregate from "visits_allowed" where "created_at" LIKE $1
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. (SQL: select count(*) as aggregate from "visits_allowed" where "created_at" LIKE 2017-05-30 %)
Can someone help me to find a solution.
Please try this instead :
foreach ($hours as $hour) {
$chart[$hour]['hour'] = $hour;
$chart[$hour]['allowed'] = VisitsAllowed::where('created_at', '=', Carbon::parse($date)->format('Y-m-d'))->count();
$chart[$hour]['denied'] = VisitsDenied::where('created_at', '=', Carbon::parse($date)->format('Y-m-d'))->count();
}
Not the prettiest solution but testing if the date (say 2017-05-30) is between: yyyy-mm-dd 00:00:00 and yyyy-mm-dd 23:59:59 works.
$chart[$hour]['allowed'] = VisitsAllowed::where('created_at', '>=', Carbon::parse($date )->format('Y-m-d') . ' 00:00:00')
->where('created_at', '<=', Carbon::parse($date )->format('Y-m-d') . ' 23:59:59')
->count();
$chart[$hour]['denied'] = VisitsDenied::where('created_at', '>=', Carbon::parse($date )->format('Y-m-d') . ' 00:00:00')
->where('created_at', '<=', Carbon::parse($date )->format('Y-m-d') . ' 23:59:59')
->count();

Doctrine Datetime and where condition

I am writing a Doctrine 2.3 Query and I am facing some issues:
The SQL Query which I am reflecting was:
SELECT *
FROM `entry`
WHERE `plate` LIKE '%'
AND `recognition_datetime` BETWEEN '2013-03-13 22:20:18'
AND '2013-03-13 22:20:20';
I am getting the out put with the rows selected.
Doctrine which I am trying:
Opt 1:
$qry = $this->manager()->createQueryBuilder()
->from($this->entity, 'e')
->select('e');
$qry->where('e.plate like :plate');
$qry->setParameter('plate', $plate);
$qry->add('where', "e.datetime between '2013-03-13 22:20:18' and '2013-03-13 22:20:20'");
$qry->setMaxResults( $limit );
It out puts only the first where condition:
SELECT e FROM Myproject\Domain\result e WHERE e.plate like '%'
Opt 2:
$qry = $this->manager()->createQueryBuilder()
->from($this->entity, 'e')
->select('e');
$qry->where('e.plate like :plate');
$qry->setParameter('plate', $plate);
$qry->andWhere('e.datetime BETWEEN :monday AND :sunday')
->setParameter('monday', $fromdate->format('Y-m-d H:i:s'))
->setParameter('sunday', $todate->format('Y-m-d H:i:s'));
It prints only the second where as query. Can some one help me how to write multiple where/And/or condition?
After some Research I found few thing which solved my problems:
Query Generation:
//CREATING QUERY BUILDER
$qry = $this->manager()->createQueryBuilder()
->from('YOUR_ENTITY_HERE', 'e')
->select('e');
//LIKE
$ex1 = $qry->expr()->like('e.user', "'".$user."'");
//BETWEEN
$ex2 = $qry->expr()->between('e.datetime',"'".$datetime."'","'".$dateto."'");
//IN
$ex3 = $qry->expr()->in('e.country', $country);
//ADDING ALL EXPRESSION TO ONE INBETWEEN EXPRESSION "AND" OPERATION
$Query = $qry->expr()->andX($ex1,$ex2,$ex3);
//ADDING ALL EXPRESSION TO ONE INBETWEEN EXPRESSION "OR" OPERATION
$Query = $qry->expr()->orX($ex1,$ex2,$ex3);
//ADDING TOTAL EXPRESSIONS TO WHERE
$qry->where($Query);
//GENERATE QUERY
$qry->getQuery();
//FINAL OPERATIONS
//EXECUTE
$qry->execute();
//GET ARRAY OUT PUT
$qry->getArrayResult();
//GET DB OBJECT
$qry->getResult();
Other Methods for Providing IN Operations:
OTHER WAY TO USE IN OPERATION:
$country=array('Us','UK','IND','BE');
$exp = $this->manager()->getExpressionBuilder();
$qry = $this->manager()->createQueryBuilder()
->select('e')
->from('YOUR_ENTITY_HERE', 'e')
->add('where', $exp->in('e.country', $country));

how to convert count(*) and group by queries to yii and fetch data from it

I want to convert this query in yii
SELECT count(*) AS cnt, date(dt) FROM tbl_log where status=2 GROUP BY date(dt)
and fetch data from that. I try this command (dt is datetime field):
$criteria = new CDbCriteria();
$criteria->select = 'count(*) as cnt, date(dt)';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
but no data will fetch!
wath can I do to get data?
Probably you see no data because you need assign data to model attributes which doesn't exist.
$criteria = new CDbCriteria();
$criteria->select = 'count(*) AS cnt, date(dt) AS dateVar';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
This means that your model must have attributes cnt and dateVar in order to show your data. If you need custom query then check Hearaman's answer.
Try this below code
$logs = Yii::app()->db->createCommand()
->select('COUNT(*) as cnt')
->from('tbl_log') //Your Table name
->group('date')
->where('status=2') // Write your where condition here
->queryAll(); //Will get the all selected rows from table
Number of visitor are:
echo count($logs);
Apart from using cDbCriteria, to do the same check this link http://www.yiiframework.com/forum/index.php/topic/10662-count-on-a-findall-query/
If you use Yii2 and have a model based on table tbl_log, you can do it in model style like that:
$status = 2;
$result = Model::find()
->select('count(*) as cnt, date(dt)')
->groupBy('date(dt)')
->where('status = :status')
->params([':status' => $status ])
->all();

DBI: selectall_arrayref and columnnames

When I fetch the data this way is it possible then to access the column names and the column types or do I need an explicit prepare to reach this?
use DBI;
my $dbh = DBI->connect( ... );
my $select = "...";
my #arguments = ( ... );
my $ref = $dbh->selectall_arrayref( $select, {}, #arguments, );
Update:
With prepare I would do it this way:
my $sth = $dbh->prepare( $select );
$sth->execute( #arguments );
my $col_names = $sth->{NAME};
my $col_types = $sth->{TYPE};
my $ref = $sth->fetchall_arrayref;
unshift #$ref, $col_names;
The best solution is to use prepare to get a statement handle, as you describe in the second part of your question. If you use selectall_hashref or selectall_arrayref, you don't get a statement handle, and have to query the column type information yourself via $dbh->column_info (docs):
my $sth = $dbh->column_info('','',$table,$column); # or $column='' for all
my $info = $sth->fetchall_arrayref({});
use Data::Dumper; print Dumper($info);
(specifically, the COLUMN_NAME and TYPE_NAME attributes).
However, this introduces a race condition if the table changes schema between the two queries.
Also, you may use selectall_arrayref with the Slice parameter to fetch all the columns into a hash ref, it needs no prepared statement and will return an array ref of the result set rows, with each rows columns the key's to a hash and the values are the column values. ie:
my $result = $dbh->selectall_arrayref( qq{
SELECT * FROM table WHERE condition = value
}, { Slice => {} }) or die "Error: ".$dbh->errstr;
$result = [
[0] = { column1 => 'column1Value', column2 => 'column2Value', etc...},
[1] = { column1 => 'column1Value', column2 => 'column2Value', etc...},
];
Making it easy to iterate over results.. ie:
for my $row ( #$results ){
print "$row->{column1Value}, $row->{column2Value}\n";
}
You can also specify which columns to extract but it's pretty useless due to the fact it's more efficient to do that in your SQL query syntax.
{ Slice => { column1Name => 1, column2Name => 1 } }
That would only return the values for column1Name and column2Name just like saying in your SQL:
SELECT column1Name, column2Name FROM table...