print last executed query in controller cakephp 3 - cakephp-3.0

suppose i have a query in cakephp 3
$post = $this->Posts->get($id, [
'contain' => ['Postmeta']
]);
I want to print it like plain mysql query for example
SELECT * FROM posts....
can anyone please explain this how can i achieve this. Please answer it only in cakephp 3 environment. Is it possible to print it in controller as normal mysql query ? please do not mention queries.log file solution. beacause it is time taking to open file and see the query after every executed query in queries.log file in that is look in cakephp style
Thanks

In Controller, We need to write two lines after query code as follows
$post = $this->Posts->get($id, [
'contain' => ['Postmeta']
]);
echo "<pre>";
print_r(debug($post));die;
It will show all result along with sql query syntax.
Here we are using debug for show result along with sql query.

Query:
$post = $this->Posts->get($id, [
'contain' => ['Postmeta']
]);
For Print/Get SQL Statement of above query you can use debug() function as follow in controller:
$post = $this->Posts->get($id, [
'contain' => ['Postmeta']
]);
debug($post);

Just write:
die(print_r($post));

Related

How to properly use Yii2 querybuilder insert method?

I was trying to use the QueryBuilder object to generate a properly escaped INSERT statement. The database table name is generated using an uploaded file's name and there'd be multiple tables, so using a model here is not really an option.
The code I tried to use was this:
$params = [
"index" => $row["A"],
"description" => $row["B"],
];
$conn->createCommand(
$qb->insert($tableName, [
"Index" => ":index",
"Description" => ":description",
], $params),
$params
)->execute();
The SQL error message I got was this that the number of parameters did not match the number of tokens.
My primary problem was that the documentation does not properly explain what the $params variable should be. I found out that it should be an empty, but initialised array, so basically $params = [];.
Also, since the function uses $params as a reference, they are already processed by the QueryBuilder object and I don't need to escape my values two times.
The final code that worked was this:
$params = [];
$conn->createCommand(
$qb->insert($tableName, [
"Index" => $row["A"],
"Description" => $row["B"],
], $params),
$params
)->execute();
I hope this helps anyone out there sometime.
It is simple as that:
$conn->createCommand()->insert($tableName, [
"Index" => $row["A"],
"Description" => $row["B"],
])->execute();
The yii\db\Command::insert() does the escaping for you. E.g.:
$a = "a'b\"";
echo \Yii::$app->db->createCommand()->insert('t', ['a' => $a])->getRawSql() . "\n";
returns
INSERT INTO `t` (`a`) VALUES ('a\'b\"')

Add a prefix to values when using a yii\db\Query

Is there a way to add a prefix to values when using a DB query to get the data from a database? I have used a var as example to show you how I want it to be.
$query = (new \yii\db\Query())->select(['name' , 'product_image."$prefix"' ])->from('products');
Lets say that I want to add after every image path a prefix like _250x250, so the final output will be pathToImage_250x250 or uploads/pathToImage_250x250.
You may use yii\db\Expression to create more advanced selects. For example for MySQL you may use CONCAT() function for this:
$query = (new \yii\db\Query())
->select([
'name',
'product_image' => \yii\db\Expression('CONCAT(product_image, :suffix)', [
':suffix' => '_250x250',
]),
])
->from('products');

How to make multiple UPSERT in Yii2?

I am using Yii2 advance template. I have to insert 1000 to 2000 records in MySql Database.
Is it possible to make Multiple UPSERT Query in Yii2.
Please help me with your suggestion/answers. Thank you.
Since version 2.0.14 you have upsert() available.
Your code could look something like this:
$insertValues = [
'timestamp' => gmdate('YmdH'),
'entry_id' => $this->id,
'view_count' => 1,
];
$updateValues = ['view_count' => new \yii\db\Expression('table_name.view_count + 1')];
Yii::$app->db->createCommand()->upsert('table_name', $insertValues, $updateValues)->execute();
You can find the full documentation here: https://www.yiiframework.com/doc/api/2.0/yii-db-command#upsert()-detail
Try with modified batchInsert() method:
$db = \Yii::$app->db;
$sql = $db->queryBuilder->batchInsert($table, $fields, $rows);
$db->createCommand($sql . ' ON DUPLICATE KEY UPDATE')->execute();

Use IN clause in updateAll() method in CakePHP 3.x

I am using Cakephp 3.x and i want to update my single field for multiple ids. Something like this..
UPDATE mytable SET `status` = '1' WHERE ID IN (1,2,3)
Currently i am using query to perform this action using cakpehp
$this->Leaveregisters->query()
->update()
->set(['leaveregister_status' => $this->request->data('status')])
->where(['leaveregister_id IN ('.$this->request->data('final_ids_string').')'])
->execute();
Well this does the trick for me but i want this to be performed using cakephp 3.xs' ORM method .. so i am trying to use this instead
$table->updateAll(['field' => $newValue], ['id' => $entityId]);
But this code is for single id only which i do not want.. i also do not want to use foeach loop to perform the same action. Instead i want an ID to be passed via array or comma seperated in any case and want to perform the same action.
Is there any way i can perform the same thing using ORM method using cakephp 3.x
Thanks
usinga updateAll or a query() objects to do a bulk update is the same thing as you can read in the manual at the end of this paragraph
so you can do
$this->Leaveregisters->query()
->update()
->set(['leaveregister_status' => $this->request->data('status')])
->where(['leaveregister_id IN' => [1,2,3])
->execute();
or
$this->Leaveregisters->updateAll(
['leaveregister_status' => $this->request->data('status')]
['leaveregister_id IN' => [1,2,3]);
remember then when usin IN clause you have to pass an array. Read this part of the manual on how to create IN clause
You have to use array datatype for pass in IN CLAUSE
$in_condition= explode(",",$this->request->data('final_ids_string'));
$this->Leaveregisters->query()
->update()
->set(['leaveregister_status' => $this->request->data('status')])
->where(['leaveregister_id IN' => $in_condition])
->execute();
With updateAll() of Model
$table->updateAll(array(
// new values
),
array('id' => array(1,2,3,4,5,6))
);

How do I take a mysql query and print the results on a cakephp page

With links to each user.
For example. "SELECT * FROM users WHERE rating > 50" this query yields 120 results... how to print those results on a page in order of rating with links to each profile..
a leaderboard if you will
A good place to start would be to review the docs at http://book.cakephp.org/ but in short it will follow Cake's MVC principles. You'll need a model to interact with the database and pass this data back to a controller. The controller will then pass that information to the relevant view script and which point you can layout the recordset as you wish.
First, you should read up on CakePHP like #simnom has suggested. Once you do, your query and view code should look something like this:
Users Controller:
$users = $this->User->find('all', array('order'=> array('User.rating' => 'desc'), 'conditions'=>array('User.rating >' => '50')));
$this->set('users', $users);
View Code:
<?php
foreach ($users as $user):
echo $this->Html->link("View User", array('controller' => 'users', 'action' => 'view', $user['id']));
endforeach;
?>