I'm writing some queries for the SQL Manager in Prestashop.
I want to group by month like so:
SELECT AVG(total_products)
FROM ps_order_invoice
GROUP BY YEAR(delivery_date), MONTH(delivery_date)
But the SQL Manager refuse to save it, displaying for only message "Error".
I could not find more information about the limitation on the SQL Manager except only SELECT queries are accepted.
However, I can save the query if I remove the YEAR and MONTH functions.
Note: Unfortunately, I don't have access to the phpmyadmin
I installed a fresh prestashop-1.6.0.6 and was able to get your error.
After inspecting the code I found that the problem comes from the RequestSql class.
The cutAttribute method can't parse attributes like "YEAR(delivery_date)". It returns a string like "YEARdelivery_date" instead of "delivery_date".
To solve this problem you can override this class and use the cutAttribute method from the last prestashop version available.
Create a file named "RequestSql.php" located in "override/classes" with this content:
class RequestSql extends RequestSqlCore
{
/**
* Cut an attribute with or without the alias
*
* #param $attr
* #param $from
* #return array|bool
*/
public function cutAttribute($attr, $from)
{
$matches = array();
if (preg_match('/((`(\()?([a-z0-9_])+`(\))?)|((\()?([a-z0-9_])+(\))?))\.((`(\()?([a-z0-9_])+`(\))?)|((\()?([a-z0-9_])+(\))?))$/i', $attr, $matches, PREG_OFFSET_CAPTURE)) {
$tab = explode('.', str_replace(array('`', '(', ')'), '', $matches[0][0]));
if ($table = $this->returnNameTable($tab[0], $from)) {
return array(
'table' => $table,
'alias' => $tab[0],
'attribut' => $tab[1],
'string' => $attr
);
}
} elseif (preg_match('/((`(\()?([a-z0-9_])+`(\))?)|((\()?([a-z0-9_])+(\))?))$/i', $attr, $matches, PREG_OFFSET_CAPTURE)) {
$attribut = str_replace(array('`', '(', ')'), '', $matches[0][0]);
if ($table = $this->returnNameTable(false, $from, $attr)) {
return array(
'table' => $table,
'attribut' => $attribut,
'string' => $attr
);
}
}
return false;
}
}
And remove the file "cache/class_index.php" otherwise the override won't be find.
Related
I'm trying to figure out how I can get the query result like $residence into the data array. because whem im doing this is gives me the error Array to string conversion. Is there any possible way to convert the query result to a normal string?
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function insert(Request $request)
{
$id = auth()->user()->id;
$title = $request->input('title');
$clientid = $request->input('client');
$startdate = $request->input('startdate');
$enddate = $request->input('enddate');
$starttime = $request->input('starttime');
$endtime = $request->input('endtime');
$description = $request->input('description');
$firstname = DB::select('select firstname from clients where id='.$clientid);
$lastname = DB::select('select lastname from clients where id='.$clientid);
$housing = DB::select('select housing from clients where id='.$clientid);
$housenr = DB::select('select housenr from clients where id='.$clientid);
$residence = DB::select('select residence from clients where id='.$clientid);
$residencestring = json_encode($residence);
$data=array(
"uuid"=>$id,
"title"=>$title,
"residence"=>$residencestring,
"startdate"=>$startdate,
"enddate"=>$enddate,
"starttime"=>$starttime,
"endtime"=>$endtime,
"description"=>$description,
"firstname"=>$firstname,
"lastname"=>$lastname,
"housing"=>$housing,
"housenr"=>$housenr
);
//dd($data);
DB::table('tasks')->insert($data);
return redirect('/todo');
}
Notice how you are doing one query for each field? Also, you are getting an array on each query, since the DB::select returns an array with one row, not the row directly as you think.
I would use Query Builder for this for a more elegant solution:
$client = DB::table('clients')->where('id', $clientid)->first();
With this, you have an object named $client that has all the fields from that row.
Then, you can just update the row as follows:
$data = [
'lastname' => $client->lastname,
'firstname' => $client->firstname
];
You could even make it more "Laravel" by using Models.
App/Models/Client.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Client extends Model {
protected $guarded = ['id'];
}
Then your code would look something like this:
<?php
use App\Models\Client;
public function insert(Request $request)
{
....
$client = Client::findOrFail($clientid);
$data = [
'lastname' => $client->lastname,
'firstname' => $client->firstname
];
....
}
The findOrFail function gives you the first register it finds on the table based, equivalent to a "where id=$clientid"
You could go even further and insert using Eloquent as well, as so:
$task = new Task;
$task->lastname = $client->lastname;
$task->firstname = $client->firstname;
$task->save();
or:
$task = Task::insert($data);
where Task is a Model as described previously.
So big thanks to #JoeGalind1! The solution was pretty simple, I had to use the build-in query builder. Instead of using an oldschool query.
This is the solution that worked for me!
$client = DB::table('clients')->select('*')->where('id', $clientid)->first();
once you made this query you can easily call it like this:
$data=array(
"residence"=>$client->residence,
);
Now there are no problems with string conversion and arrays when you need to insert afterwards.
I am working on a Laravel project. I ran these commands and successfully created notifications table.
php artisan notifications:table
php artisan migrate
All of the things were going perfectly. Later on I created a Model name "NotificationsForAdmin" with migration named "notifications_for_admin", then later on I drooped this table. Now when I am trying to generate some notifications then it is showing me this error, I dont know whats going on I have notifications table in database that is needed for laravel notifications with perfect schema. the error is :
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'followup.notification_for_admins' doesn't exist (SQL: select * from `notification_for_admins` where `notification_for_admins`.`user_id` = 2 and `notification_for_admins`.`user_id` is not null)
My notifications is :
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use App\User;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Messages\MailMessage;
use App\Events\NewEmailReceivedEvent;
use Auth;
class NewEmailReceived extends Notification
{
use Queueable;
public $sender_id, $receiver_id, $sender_name, $receiver_name, $sender_type, $receiver_type, $type, $recipient, $from_email, $subject, $message, $image, $receiver_image, $attachments, $sizesOfAttachments, $originalFileNames, $thread_id, $id_of_email;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($sender_id, $receiver_id, $sender_name, $receiver_name, $sender_type, $receiver_type, $type, $recipient, $from_email, $subject, $message, $image, $receiver_image, $attachments, $sizesOfAttachments, $originalFileNames, $thread_id, $id_of_email)
{
$this->sender_id = $sender_id;
$this->receiver_id = $receiver_id;
$this->sender_name = $sender_name;
$this->receiver_name = $receiver_name;
$this->sender_type = $sender_type;
$this->receiver_type = $receiver_type;
$this->type = $type;
$this->recipient = $recipient;
$this->from_email = $from_email;
$this->subject = $subject;
$this->message = $message;
$this->image = $image;
$this->receiver_image = $receiver_image;
$this->attachments = $attachments;
$this->sizesOfAttachments = $sizesOfAttachments;
$this->originalFileNames = $originalFileNames;
$this->thread_id = $thread_id;
$this->id_of_email = $id_of_email;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
$notifications = Auth::user()->notifications;
if ($notifications[7]->shown == 1) {
return ['mail', 'database'];
}
else{
return ['database'];
}
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'sender_id' => $this->sender_id,
'receiver_id' => $this->receiver_id,
'sender_name' => $this->sender_name,
'receiver_name' => $this->receiver_name,
'sender_type' => $this->sender_type,
'receiver_type' => $this->receiver_type,
'type' => $this->type,
'recipient' => $this->recipient,
'from_email' => $this->from_email,
'subject' => $this->subject,
'message' => $this->message,
'image' => $this->image,
'receiver_image' => $this->receiver_image,
'attachments' => $this->attachments,
'sizesOfAttachments' => $this->sizesOfAttachments,
'originalFileNames' => $this->originalFileNames,
'thread_id' => $this->thread_id,
'id_of_email' => $this->id_of_email,
];
event(new NewEmailReceivedEvent($NewEmailReceivedRequest));
return $NewEmailReceivedRequest;
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject("New email from ".$this->sender_type)
->greeting('Hello!')
->markdown('mails.NewEmailReceived' , ['recipient_name' => $this->receiver_name , 'subject' => $this->subject , 'mailMessage' => str_limit($this->message, 50) , 'avatar' => $this->image]);
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
I shall be very thankfull if someone could help me on this.
It seems your notifications relation on your User object still references NotificationsForAdmin.
If you do not specify the table for a model, the table is automatically generated as a snake_case string of the model name. In the case of NotificationsForAdmin this becomes notification_for_admins.
Add the public property $table to your NotificationsForAdmin with the name of the table where your notifications are stored as the value. This should fix your problem.
In controller i have:
public function actionGetItems()
{
$model = new \app\models\WarehouseItems;
$items = $model->find()->with(['user'])->asArray()->all();
return $items;
}
In WarehouseItem model i have standard (created by gii) relation declaration:
public function getUser()
{
return $this->hasOne('\dektrium\user\models\User', ['user_id' => 'user_id']);
}
How can i control which column data do i get from "user" relation? I currently get all columns which is not good as that data is being sent to Angular in JSON format.
Right now i have to loop trough $items and filer out all columns i dont want to send.
You should simply modify the relation query like this :
$items = \app\models\WarehouseItems::find()->with([
'user' => function ($query) {
$query->select('id, col1, col2');
}
])->asArray()->all();
Read more : http://www.yiiframework.com/doc-2.0/yii-db-activequerytrait.html#with()-detail
Your code should go this way.
public function actionGetItems()
{
$items = \app\models\WarehouseItems::find()
->joinWith([
/*
*You need to use alias and then must select index key from parent table
*and foreign key from child table else your query will give an error as
*undefined index **relation_key**
*/
'user as u' => function($query){
$query->select(['u.user_id', 'u.col1', 'u.col2']);
}
])
->asArray()
->all();
return $items;
}
Inside WarehouseItem model
/**
* #return ActiveQuery
*/
public function getUser()
{
$query = User::find()
->select(['id', 'col1', 'col2'])
->where([
'id' => $this->user_id,
]);
/**
* Default hasOne, setup multiple for hasMany
* $query->multiple = true;
*/
return $query;
}
I'm trying to make a module for Drupal 7.x. At a certain point I want to use a sql query (JOIN). When I try the query in MYSQL it works. But when I want to try it in Drupal, the array is empty.
So I guess there is a difference between the sql query and the drupal query (mayby the implemantion is different).
SQL Query
SELECT * FROM friends
INNER JOIN users
ON friends.uid=users.uid
Drupal implementation
function project_myfriends(){
// Use database API to retrieve tasks
$query = db_select('friends', 'f');
$query->join('users', 'u', 'f.uid = u.uid'); // JOIN
$query->fields('u', array('name'))
->execute();
return $query;
}
/**
* Implements hook_block_view().
*/
function project_block_view($delta = ''){
switch ($delta) {
case 'project':
$block['subject'] = t('My Friends');
// Use our custom function to retrieve data
$result = project_myfriends();
$items = array();
var_dump($result);
foreach($result as $friend){
$items[] = array(
'data' => $friend->name,
);
}
// No tasks
if (empty($items)) {
$block['content'] = t('No friends.');
}
else {
// Pass data trough theme function
$block['content'] = theme('item_list', array(
'items' => $items));
}
}
return $block;
}
Thx in advance
You forgot to fetch your result query:
$result = project_myfriends()->execute()->fetchAll();
var_dump($result);
I'm trying to do a query with Zend Framework 2 where I have a SELECT inside a JOIN statement. So far, here's what I've tried, but injecting the SELECT object into the first parameter of join() doesn't seem to be working. I've resorted to such an approach since I need to order the results first before doing any grouping. Any ideas on how to get it working?
public function getSearchKeyword($keyword, $limit)
{
$select = $this->keywords->getSql()->select();
$subquery = $this->pages->getSql()->select();
$subWhere = new \Zend\Db\Sql\Where();
$subWhere->equalTo('delete_flag', 'n')
->equalTo('published_flag', 'y');
$subquery->where($subWhere);
$where = new \Zend\Db\Sql\Where();
$where->like('keyword', '%' . $keyword . '%')
->equalTo('delete_flag', 'n');
$select->columns(array('display' => 'keyword', 'url'))
->join(array('sub' => $subquery), 'sub.page_id = keywords.page_id', array())
->where($where)
->group(array('keywords.page_id', 'keywords.keyword'))
->order(array('rank', 'keyword'))
->limit($limit);
$row = $this->tableGateway->selectWith($select);
return $row;
}
The query I'm trying to write is below:
SELECT keywords.keyword AS display, keywords.url
FROM keywords
INNER JOIN
(
SELECT * FROM pages WHERE published_flag = 'y' AND delete_flag = 'n' ORDER BY page_id DESC
) pages
ON pages.page_id = keywords.page_id
WHERE published_flag = 'y'
AND delete_flag = 'n'
AND keywords.keyword LIKE '%?%'
GROUP BY display, page_id;
I was working around the same problem and did not found a standard way to solve it. So I got a working but not zf2 standard one
Create a small interface to mannage Db conections
Implements it as a small class to get a connection PDO object to
your database
execute your arbitrary querys
Code sample
// Filename: /module/MyTools/src/MyTools/Service/DbModelServiceInterface.php
namespace MyTools\Service;
interface DbModelServiceInterface
{
/**
* Will return the result of querying the curret database
*
* #param type $query
* #result mixed
*/
public function dbQuery($query);
/**
* Will return a connection object that links to curret database
*
* #result mixed
*/
public function getConnection();
}
The class implementing the interface. It creates and offers a PDO connection. Note: It needs extra code to close conns and to perfeorm security adm...
It test it and is completely functional.
code:
// Filename: /module/MyTools/src/MyTools/Service/DbModelServiceMySql.php
namespace MyTools\Service;
use MyTools\Service\DbModelServiceInterface;
use PDO;
class DbModelServiceMySql implements DbModelServiceInterface
{
protected $driverConfig;
protected $connection;
protected $isconnected = FALSE;
protected $dbname = '';
/**
* Creates a connection to main database
*/
public function __construct()
{
$driverConfig = self::getDriverDef();
$this->driverConfig = $driverConfig; // new PDO($driverConfig['dsn'], $driverConfig['username'], $driverConfig['password']);
$this->_connect();
}
protected function _connect(){
$dsn = (isset($this->driverConfig['dsn'])) ? $this->driverConfig['dsn'] : '';
$username = (isset($this->driverConfig['username'])) ? $this->driverConfig['username'] : '';
$password = (isset($this->driverConfig['password'])) ? $this->driverConfig['password'] : '';
if( ($dsn) && ($username) && ($password)){
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ];
try {
$this->connection = new PDO($dsn, $username, $password, $options);
$this->isconnected = TRUE;
$this->_setdbname($dsn);
} catch (Exception $ex) {
throw new RuntimeException('YOUR ERROR MESSAGE.');
}
}
return $this->isconnected;
}
protected function _setdbname($dsn){
if($dsn){
$chunks = explode(';', ''.$dsn);
foreach($chunks as $chunk){
if(strpos('***'.$chunk, 'dbname') > 2){
$nombre = explode('=', $chunk);
$this->dbname = $nombre[1];
break;
}
}
}
}
/**
* {#inheritDoc}
*/
public function dbQuery($query) {
if($this->connection){
$resultset = $this->connection->query($query);
if($resultset){
return $resultset->fetchAll(PDO::FETCH_ASSOC);
}else{
return ['Error' => 'YOUR CUSTOM ERROR MESSAGE.'];
}
}else{
return ['Error' => 'OTHER CUSTOM ERROR MESSAGE'];
}
}
public static function getDriverDef()
{
$autoloadDir = __DIR__ . '../../../../../../config/autoload/';
$credentialsdb = include $autoloadDir . 'local.php';
$globaldb = include $autoloadDir . 'global.php';
$def = (isset($globaldb['db'])) ? $globaldb['db'] : array();
$credentials = (isset($credentialsdb['db'])) ? $credentialsdb['db'] : $credentialsdb;
return array_merge($def, $credentials);
}
/**
* {#inheritDoc}
*/
public function getConnection() {
if($this->connection){
return $this->connection;
}else{
return 'Error: YOUR CUSTOM ERROR MESSAGE';
}
}
/**
* {#inheritDoc}
*/
public function getDbName(){
return $this->dbname;
}
}
Now you have a class you can instantiate elsewhere to perform the querys you need.
use:
code:
$myQuery = 'the very very complex query you need to execute'
$myDbConn = new MyTools\Service\DbModelServiceMySql();
$result = $myDbConn->dbQuery($myQuery);
If success you got a resulset array of pairs columnName => value
You can try this one.
$select->columns(array('display' => 'keyword', 'url'))
->join(array('sub' => 'pages'), 'sub.page_id = keywords.page_id',
array(), $select::JOIN_INNER)
->where($where)
->group(array('keywords.page_id', 'keywords.keyword'))
->order(array('rank', 'keyword'))
->limit($limit);
In your code, you are getting all keywords which page_id's is in sub page_id where delete_flag = 'n' and published_flag = 'y'.
join(..., 'sub.page_id = keywords.page_id', array())
When you don't need any columns of pages table, you can use IN instead of JOIN.
For example when you need to know which keywords are in which pages, you should use JOIN, but when you need to know which keyboards are in any pages, you can use IN statement.
Anyway :
There is no standard way in ZF2 but you can try following code.
public function getSearchKeyword($keyword, $limit)
{
$select = $this->keywords->getSql()->select();
$subquery = $this->pages->getSql()->select();
$subWhere = new \Zend\Db\Sql\Where();
$subWhere->equalTo('delete_flag', 'n')
->equalTo('published_flag', 'y');
$subquery->columns(array('page_id'))
->where($subWhere);
$where = new \Zend\Db\Sql\Where();
$where->like('keyword', '%' . $keyword . '%')
->equalTo('delete_flag', 'n')
->in('keywords.page_id', $subquery);
$select->columns(array('display' => 'keyword', 'url'))
->where($where)
->group(array('keywords.page_id', 'keywords.keyword'))
->order(array('rank', 'keyword'))
->limit($limit);
$row = $this->tableGateway->selectWith($select);
return $row;
}
I've faced a similar issue. Since the FROM table and Subquery's FROM table were different i got an error.
My workaround was to extract the SQL and create a statement.
$sql = $select->getSqlString(new \Zend\Db\Adapter\Platform\Mysql());
$stmt = $this->getAdapter()->createStatement($sql);
$stmt->prepare($sql);
$result = $stmt->execute();
$resultSet = new ResultSet(); \\ Class Zend\Db\ResultSet\ResultSet
$resultSet->initialize($result);