CAKEPHP 3 : Select * and sum() in one statement - cakephp

I am trying to fetch result from database table with SELECT * and SUM() function.
The sql query is :
SELECT * ,SUM(msg_send) AS msg_send FROM msg_campaigns
Now how to write this query in cakephp3.
I am trying this :
$this->loadModel('MsgCampaigns');
$SmsDetails = $this->MsgCampaigns->find('all',[
'conditions'=>['YEAR(date_time)'=>date('Y')],
'fields'=>['msg_send'=>'SUM(msg_send)','msg_failed'=>'SUM(msg_failed)']
]);
But I do not know how to use SELECT * . Please help

Check the CakePHP Query Builder on how to use SQL functions and how to select all fields.
$query = $this->MsgCampaigns->find();
$query
->select([
'sum_msg_send' => $query->func()->sum('msg_send'),
'sum_msg_failed' => $query->func()->sum('msg_failed')
])
// passing the table instance to the `select` function, selects all fields
->select($this->MsgCampaigns);
$query->execute();

Related

CakePHP 3.x case statement on order

I am trying to use a CASE statement on the order of a MySQL statement in CakePHP 3.x app. The simple select is as follows:
$articles = $this->Articles->find()
->where($conditions)
->order(function ($exp, $q) {
return $exp->addCase(
[
$q->newExpr()->gt('Articles.modified', (new Time())->subDays(365)) // article has been updated in the last x days
],
['priority'], # values matching conditions
['string'] # type of each value
);
})
->limit(15)
->all();
The following SQL is generated:
SELECT `Articles`.`id` AS `Articles__id`, ....
FROM `articles` `Articles`
WHERE (`publish` < :c0 AND `Articles`.`publish` > :c1)
ORDER BY CASE WHEN `Articles`.`modified` > :c2 THEN :param3 END LIMIT 15
The case statement is not correct because it is missing the DESC order which should come after the 'END' - see this fiddle:
http://sqlfiddle.com/#!9/8df161/5
I'm not sure if this is a limitation with how CakePHP handles CASE?
Further I require a second order after the case statement to order by 'publish' desc.
Expressions passed to Query::order() must generate everything required by the ORDER BY clause, including the direction keyword.
If the expression that you're using doesn't support that, then you can use Query::oderAsc() or Query::oderDesc(), which will append the respective direction keyword accordingly.
$query = $this->Articles->find();
$query
->where($conditions)
->orderDesc(
$query->newExpr()->addCase(/* ... */)
)
// ...
See also
Cookbook > Database Access & ORM > Query Builder > Selecting Data

Reduce arrays where values are equals

It's a simple question I think, but i can't handle this.
If you see the image, here is my DB with multiple Usernames and "instances_id". If I var_dump this I have 11 arrays (and that's normal).
Is there a way to reduce arrays where "instance_id" is equal?
So that I have the first array containing "Alessio,Giorgio", the second one "Alessio,Giovanni" etc.
I use laravel... I hope you can help me
You could use combination of GROUP BY with GROUP_CONCAT to retrieve directly from db:
$result = DB
::table('example')
->selectRaw('instance_id, GROUP_CONCAT(Username)')
->groupBy('instance_id')
->get();
Or via laravel collection:
$result = DB::table('example')->get();
$result = $result
->groupBy('instance_id')
->map(function($group){
$data = $group->first();
$data->Username = $group->pluck('Username')->implode(',');
return $data;
})
->values();
Try..
SELECT * FROM tableName GROUP BY fieldName;
The following query will select all fields along with distinct zip field.
There are two ways.
1)select *
from table
group by field1
2) select distinct on field1 *
from table

CakePHP 3 DISTINCT has no effect on generated query

CakePHP 3.5.13
$query = $Substances->find()->select(['id']);
debug($query->sql());
Produces:
'SELECT Substances.id AS `Substances__id` FROM substances Substances'
Trying to do the MySQL equivalent of DISTINCT() by changing the query to:
$query = $Substances->find()->select(['id'])->distinct(['id']);
Results in exactly the same query string as without ->distinct():
'SELECT Substances.id AS `Substances__id` FROM substances Substances'
Why is this? According to the documentation, that's how you write a DISTINCT() query using Cake's ORM.

Cakephp How to use SQL month function in cakephp find method

I have a query like
SELECT count(id),DATE_FORMAT(created,'%M') from searches group by month(created)
The output that I got like
count(id) DATE_FORMAT(created,'%M')
16 August
2 September
I applied this query in cakephp find method like below
$total = $this->Searches->find('count',[
'fields'=>['Searches.id',DATE_FORMAT('created','%M')],
'group' =>[month('Searches.created')]
]);
1st I am getting error date_format() expects parameter 1. How can I apply my top sql query in cakephp find method ?
I am using cakephp 3 version.
The query builder has a func() method that allows you to use SQL functions.
http://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions
$time = $query->func()->date_format([
'created' => 'identifier',
"'%M'" => 'literal'
]);
You can then use that $time variable in your query.

how to use "find_in_set" in cakephp find method

I have a table in which comma seprated id of another table i want to use the following query in cakephp in proper form with find function
"select * from special_offers where find_in_set('".$storeId."', stores) and user_id = '". $userId ."'";
Use like this
$data = $this->SpecialOffer->find('all',array('conditions' => array('SpecialOffer.user_id' => $userId ,'FIND_IN_SET(\''. $storeId .'\',SpecialOffer.stores1)')));
Hope this may help you

Resources