CakePHP 3: How to count and retrieve data for different periods in one query? - mysql

I want to count and retrieve data for different periods like today, total, this week, etc by DATETIME created field.
How to count for example this_week?
Here is starting code:
public function findTotalRegistered(Query $query, Array $options)
{
$total = $query->func()->count('id');
$query
->select([
'total' => $total,
//'today' => $today,
//'this_week' => $this_week,
//'this_month' => $this_month,
//'this_year' => $this_year
]);
return $query;
}

You can achieve this by doing sub-query:
public function findTotalRegistered(Query $query, Array $options)
{
$total = $query->func()->count('id');
$query
->select([
'total' => $total,
'today' => $query->where('DATE(created) = CURDATE()')->count(),
'this_week' => $query->where('YEARWEEK(DATE(created), 1) = YEARWEEK(CURDATE(), 1))')->count(),
'this_month' => $query->where('DATE_SUB(NOW(), INTERVAL 1 MONTH)')->count(),
'this_year' => $query->where('YEAR(created) = YEAR(CURDATE())')->count()
])
->group(created);
return $query;
}
Thanks

Related

i want to separate Date and time format in json from laravel

how are you ?
i have Laravel project and the json return date like this
2019-05-04
and time like this
18:00:00
how can i make it like this
year : 2019
month : MAY
Day : 04
time : 06:00
timeS : PM
my code now is this
the model
public $table = 'bookings';
protected $dates = [
'date',
'created_at',
'updated_at',
'deleted_at',
];
protected $fillable = [
'date',
'time',
'user_id',
'type_id',
'persons',
'order_no',
'created_at',
'updated_at',
'deleted_at',
'table_cat_id',
'booking_status_id',
];
the controller is
public function index(Request $request)
{
$user = Auth::user();
if(isset($user->id)){
$bookings = Booking::where('user_id', $user->id)->get();
}else{
$bookings = null;
}
return response()->json($bookings);
}
You dont have added your code to the question, so i will try provide an answer using carbon:
//add this line to your controller:
use Carbon\Carbon;
//Parse the date you want to use:
$date = Carbon::parse($date); //Or use Carbon::now() to get the current time
$year = $date->year;
$month = $date->format('F');
$day = $date->day;
$timeS = $date->format('A');
$time = $date->format('H:i');
//now return your json:
return response()->json([
'year' => $year,
'month' => $month,
'day' => $day,
'timeS' => $timeS,
'time' => $time,
]);
Update
To work with your code:
Choose the date you want to use, like created_at or updated_at.
Then, do something like this:
//add this line to your controller:
use Carbon\Carbon;
public function index(Request $request)
{
$user = Auth::user();
if(isset($user->id)){
$bookings = Booking::where('user_id', $user->id)->get();
//With the created_at field:
foreach($bookings as $booking){
$date = Carbon::parse($booking->created_at);
$year = $date->year;
$month = $date->format('F');
$day = $date->day;
$timeS = $date->format('A');
$time = $date->format('H:i');
$dates = array(
'year' => $year,
'month' => $month,
'day' => $day,
'timeS' => $timeS,
'time' => $time
);
$booking->dates = $dates;
}
}else{
$bookings = null;
}
return response()->json($bookings);
}
Hope it helps.
Another solution
You can append the $dates to your model.
To do it follow this steps:
Add the $appends to your model:
protected $appends = ['dates'];
Use Carbon in your model:
use Carbon\Carbon;
Create a getDatesAttribute function in your model (it is an accessor):
public function getDatesAttribute()
{
$date = Carbon::parse($this->created_at) //You can use any date field you want
$year = $date->year;
$month = $date->format('F');
$day = $date->day;
$timeS = $date->format('A');
$time = $date->format('H:i');
return array (
'year' => $year,
'month' => $month,
'day' => $day,
'timeS' => $timeS,
'time' => $time
);
}
Now, everytime you execute a query with your model, the dates will be include to the returned collection. You can access it with:
$record->dates
Note that $record is the just an example name.
Read more about Appending Values To JSON here.

Cakephp 3 findAuth join table return array

I am attempting to implement a role based authentication system using a custom finder.
public function findAuth(\Cake\ORM\Query $query, array $options)
{
$query
->select(['id', 'username', 'passwordHash', 'locked', 'roles.role'])
->group('username')
->join([
'table' => 'user_roles',
'conditions' => ['user_roles.userid = Users.id']])
->join([
'table' => 'roles',
'conditions' => ['roles.id = user_roles.role']])
->toArray()
;
return $query;
}
The resulting mysql query i need is:
select users.id, username, passwordHash, locked, group_concat(roles.role) role from users INNER JOIN user_roles on user_roles.userid = users.id INNER JOIN roles on roles.id = user_roles.role group by users.id
What I finally ended up going with is this:
public function findAuth(\Cake\ORM\Query $query, array $options)
{
$query
->select(['id', 'username', 'passwordHash', 'locked'])
->join([
'table' => 'user_roles',
'conditions' => ['user_roles.user_id = Users.id']])
->contain(['UserRoles.Roles'])
->join([
'table' => 'roles',
'conditions' => ['roles.id = user_roles.role']])
->group(['Users.username']);
return $query;
}
This gives me a multi-dimensional array of:
user_roles[index[id, user_id, roles[id, role]]]
in my case I have 2 entries for the index (0 and 1) and I can check the role of the user with the in_array function within a foreach loop

Yii2: Group by after Order By

I have database
pls help me.
I want get listViewCount of Content of subscriber as below
SELECT
id,
subscriber_id,
content_id,
started_at,
stopped_at,
view_date FROM
(SELECT
*
FROM
content_view_log
WHERE
subscriber_id = 19
ORDER BY view_date DESC) t GROUP BY content_id;
lstViewCount when use sql above
Pls fix my sql with yii2:
public function search($params)
{
$query = ContentViewLog::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'subscriber_id' => $this->subscriber_id,
'type' => $this->type,
'site_id' => $this->site_id,
]);
$query->groupBy("content_id");
$query->orderBy("id desc");
return $dataProvider;
}

Getting an error Call to a member function getCount() on a non-object

i am using sqldataprovider and i am geting a Call to a member function getCount() on a non-object error. i dont know what have i done wrong. below is my controller code
public function actionTicketbookingreport()
{
$count = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM screen_ticket_booking_history WHERE status=:status
', [':status' => 0])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT A1.booking_id As Booking_id,
A1.booking_date As Booking_date,
A2.movie_name As Movie,
A3.theatre_name As Theatre,
A1.amount As Amount
FROM
screen_ticket_booking_history A1
LEFT OUTER JOIN movies A2 ON A1.movie_id=A2.id
LEFT OUTER JOIN theatres A3 ON A1.theatre_id=A3.id
LEFT OUTER JOIN users_backend A4 ON A3.users_backend_id=A4.id
WHERE A1.booking_date >= :start_date
AND A1.booking_date <= :end_date
AND A3.users_backend_id = :id',
'params' => [':start_date' => $year_start,':end_date'=>$year_end,':id'=> $userid],
'totalCount' => $count,
]);
// get the user records in the current page
$models = $dataProvider->getModels();
//no dataprovider
return $this->render('index',
[ 'model' => $model,
'dataProvider' => $models,
]);
}
Okey I see where what is wrong
return $this->render('index',
[ 'model' => $model,
'dataProvider' => $models,
]);
getModels() returns just an array of elements. If You are trying to generate gridView or something like that You should give whole dataProvider. So it should be
'dataProvider' => $dataProvider,

Joomla: two mysql queries model functions with one view

I am trying to run two model functions from one view. The first query appears to be working fine.
The second query returns a blank array. I noticed when printing the query to the screen that the queries appear to be joining together and are not separate, like this:
JDatabaseQueryMySQL Object ( [db:protected] => JDatabaseMySQL Object ( [name] => mysql [nameQuote:protected] => ` [nullDate:protected] => 0000-00-00 00:00:00 [dbMinimum:protected] => 5.0.4 [_database:JDatabase:private] => Curling_Schedule [connection:protected] => Resource id #19 [count:protected] => 0 [cursor:protected] => Resource id #72 [debug:protected] => [limit:protected] => 0 [log:protected] => Array ( ) [offset:protected] => 0 [sql:protected] => SELECT team_name, division FROM #_autoschedTeams ORDER BY division [tablePrefix:protected] => encex [utf:protected] => 1 [errorNum:protected] => 0 [errorMsg:protected] => [hasQuoted:protected] => [quoted:protected] => Array ( ) ) [type:protected] => select [element:protected] => [select:protected] => JDatabaseQueryElement Object ( [name:protected] => SELECT [elements:protected] => Array ( [0] => sheet, id ) [glue:protected] => , ) [delete:protected] => [update:protected] => [insert:protected] => [from:protected] => JDatabaseQueryElement Object ( [name:protected] => FROM [elements:protected] => Array ( [0] => #__autoschedPlayingSheets ) [glue:protected] => , ) [join:protected] => [set:protected] => [where:protected] => [group:protected] => [having:protected] => [columns:protected] => [values:protected] => [order:protected] => JDatabaseQueryElement Object ( [name:protected] => ORDER BY [elements:protected] => Array ( [0] => sheet ) [glue:protected] => , ) [union:protected] => [autoIncrementField:protected] => )
Model:
public function getTeams()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('team_name, division');
// From the hello table
$query->from('#__autoschedTeams');
$query->order('division');
$db->setQuery((string)$query);
$teams = $db->loadResultArray();
$div = $db->loadResultArray(1);
$divs = array_unique($div);
$result = [];
foreach($divs as $key)
{
$result[$key] = [];
foreach(array_keys($div, $key) as $index)
{
array_push($result[$key], $teams[$index]);
}
}
return $result;
}
public function getSheets()
{
// Create a new query object.
$db = JFactory::getDBO();
print_r($query);
$query = $db->getQuery(true);
// Select some fields
$query->select('sheet, id');
// From the hello table
$query->from('#__autoschedPlayingSheets');
$query->order('sheet');
//print_r($query);
$db->setQuery($query);
$result = $db->loadResultArray();
return $result;
}
}
relevant code from View:
$teams_sched = $this->get('Teams');
$sheets_sched = $this->get('Sheets');
Change the name of the variable and check with it.
If you are not getting the result again, then print the query echo $query; and check with it.
public function getSheets()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('sheet, id');
$query->from('#__autoschedPlayingSheets');
$query->order('sheet');
$db->setQuery($query);
$Sheets = $db->loadResultArray();
print_r($Sheets);
return $Sheets;
}