Joining With SQL Function In CakePHP 3 - sql

Hi there I want to change this query into cakePHP 3.0 format but the code is not working could you guys can help me to solve this problem?
Normal SQL:
SELECT COUNT(user_tag_review.id) AS user_numbers, SUM(user_rating.rating_value) AS rating_value FROM user_tag_review INNER JOIN user_rating ON user_tag_review.id = user_rating.review_id WHERE user_tag_review.recruiter_id = 2 AND user_rating.rating_id = 1
CakePHP code that I have used:
$review_table = TableRegistry::get('UserTagReview');
$query = $review_table->find();
$query->select(["user_numbers" => $query->func()->count("UserTagReview.id")])
->hydrate(false)
->join(["table" => "user_rating",
"alias" => "r",
"type" => "INNER",
"condition" => ['r.review_id = UserTagReview.id']
])
->select(["rating_value" => $query->func()->sum("r.rating_value")])
->where(["UserTagReview.recruiter_id" => $recruiter_id, "UserTagReview.rating_id = " . 1]);
$result = $query->all()->toArray();

I think simpler way to migrate that SQL to Cake is fields options in finder:
$table = TableRegistry::get('UserTagReview');
$result = $table
->find('all' , [
'fields' => [
'user_numbers' => 'COUNT(UserTagReview.id)',
'rating_value' => 'SUM(user_rating.rating_value)'
],
'join' => [
[
'table' => 'user_rating',
'alias' => 'user_rating',
'type' => 'INNER',
'conditions' => [
'UserTagReview.id = user_rating.review_id'
]
]
],
'conditions' => [
'UserTagReview.recruiter_id' => 2,
'user_rating.rating_id' => 1
]
])
->hydrate(FALSE)
->toArray();
Maybe this code is not 100% correct, but focus on fields array - if we use this as associative array, we can evaluate any sql:
'fields' => [
'alias' => 'COUNT(IF(1,1,0))'
]

Related

Error message : Unknown column 'a.id_configuration' in 'order clause'

With this code i would like print a tab with some fields in prestashop back office. But i got an error message: : Unknown column 'a.id_configuration' in 'order clause'
<?php
public function __construct()
{
parent::__construct();
$this->table = 'order_invoice'; // SQL table name, will be prefixed with _DB_PREFIX_
$this->className = 'OrderInvoice'; // PHP class name
$this->allow_export = true; // allow export in CSV, XLS..
$this->fields_list = [
'id_order_invoice' => ['title' => $this->trans('ID', [], 'Admin.Global'),'class' => 'fixed-width-xs'],
'number' => ['title' => $this->trans('Number', [], 'Admin.Global'),'class' => 'fixed-width-xs'],
'date_add' => ['title' => $this->trans('Date', [], 'Admin.Global'), 'type'=>'datetime'],
'total_products_wt' => ['title' => $this->trans('Total products', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
'total_shipping_tax_incl' => ['title' => $this->trans('Total shipping', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
'total_paid_tax_incl' => ['title' => $this->trans('Total paid', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
];
}
?>
```
Since it states it's an error within the order clause (ORDER BY), we'd edit the orderBy variable like this:
$this->_orderBy = 'id_order_invoice';
You can also edit the identifier since it seems to be using the wrong identifier to begin with:
$this->identifier = 'id_order_invoice';
Hope this helps.

Relation two database and make join yii2

Can you help me. How to relate it and make a join
. i get error has no relation named "project".
i using ActiveRecord with my code :
$posts = MaKantor::find()
->leftJoin('project.track', '`track`.`id_office` = `m_kantor`.`kantor_id`')
->with('project.track')->where(['collecting_id' => $model->collecting_id])
->all();
and config
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=project',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db_master',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
When you use with('relationName') in query, relation function needs to be defined in MaKantor model.
For example :
public function getProject()
{
return $this->hasOne(Project::className(), ['id' => 'project_id']);
}

Yii2- ArrayHelper change index of array

I have an array as follows:
[
0 => [
'name' => 'CARD'
'id' => '0'
]
1 => [
'name' => 'MOBILE'
'id' => '1'
]
2 => [
'name' => 'GIFT'
'id' => '2'
]
]
I want to change the key id to type in all the array. Is there a way to do this in Yii2 using ArrayHelper?
You can use getColumn() for this:
$result = ArrayHelper::getColumn($array, function ($data) {
return [
'name' => $data['name'],
'type' => $data['id'],
];
});
But it will not really differ from array_map() or simple foreach.
There is not an array helper for this but you could do this with a php foreach
foreach ($myArray as $key => $value) {
$myArray[$key]['type'] = $value['id'];
unset($myArray[$key]['id']);
}

Cakephp3 query with contain returns 0 results

Here is my query that works:
$query = $appointments->find();
$query->where(['Appointments.id =' => '786']);
$query->order(['date' => 'ASC']);
This returns 1 result. Now when I want to tie in the other 'belongs to' tables I use this query:
$query = $appointments->find();
$query->select(['Appointments.id', 'Appointments.start', 'Clients.name', 'Services.Name']);
$query->where(['Appointments.id =' => '786']);
$query->contain(['Clients', 'Users', 'Services']);
$query->order(['date' => 'ASC']);
This returns 0 results, am I doing something wrong?
Here is my my AppointmentsTable.php:
public function initialize(array $config)
{
parent::initialize($config);
$this->table('appointments');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Clients', [
'foreignKey' => 'client_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Services', [
'foreignKey' => 'service_id'
]);
}

yii2 file upload not working

I have followed the following guide https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md but no file is being uploaded. below is my configuration
_form
This is in a for loop so i can get an array of different records.
<?= $form->field(new UploadForm , "[$count]file")->fileInput()->label(false) ?>
view
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>...
controller
if(isset(Yii::$app->request->post()['Factsheets'])){
for($i=0 ; $i < count(Yii::$app->request->post()['Factsheets']); $i++) {
//Yii::error(print_r(Yii::$app->request->post()['Factsheets'][$i],true));
if(!empty(Yii::$app->request->post()['UploadForm'][$i]['file'])){
$file = new UploadForm();
$file->file = UploadedFile::getInstance(Yii::$app->request->post()['UploadForm'][$i], 'file');
if ($file->file && $file->validate()) {
$file->file->saveAs('uploads/' . $file->file->baseName . '.' . $file->file->extension);
}
}
}
}
post log
[Factsheets] => Array
(
[0] => Array
(
[type] => image
[factsheet_id] => 1185
[path] => ../public/filespool/2/289/Pelotas_Reprocessing.jpg
)
[1] => Array
(
[type] => tech_paper
[factsheet_id] => 1433
[path] => ?basin=pelotas
)
[2] => Array
(
[type] => factsheet
[factsheet_id] => 1844
[path] => ../public/filespool/2/289/Pelotas_Reprocessing.pdf
)
)
[UploadForm] => Array
(
[0] => Array
(
[file] =>
)
[1] => Array
(
[file] =>
)
[2] => Array
(
[file] =>
)
)
I have noticed the following in the post log now. how do i construct it?
$_FILES = [
'UploadForm' => [
'name' => [
0 => [
'file' => 'Destin_Dome.jpg'
]
1 => [
'file' => ''
]
2 => [
'file' => 'Pelotas_Reprocessing.pdf'
]
]
'type' => [
0 => [
'file' => 'image/jpeg'
]
1 => [
'file' => ''
]
2 => [
'file' => ''
]
]
'tmp_name' => [
0 => [
'file' => '/tmp/phpoPgbJ9'
]
1 => [
'file' => ''
]
2 => [
'file' => ''
]
]
'error' => [
0 => [
'file' => 0
]
1 => [
'file' => 4
]
2 => [
'file' => 1
]
]
'size' => [
0 => [
'file' => 1129373
]
1 => [
'file' => 0
]
2 => [
'file' => 0
]
]
]
]
It seems like it is failing validation however i was able to make a copy like:
if(!empty($_FILES['UploadForm']['tmp_name']['file'])){
copy($_FILES['UploadForm']['tmp_name']['file'],"/tmp/".$_FILES['UploadForm']['name']['file']);
}
fileUpload model
public $file;
public $image;
public $factsheet;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file','maxFiles' => 10],
[['image'], 'file','extensions' => 'gif, jpg'],
[['factsheet'], 'file','checkExtensionByMimeType' => false,'extensions' => 'pdf'],
];
}
I may be wrong but I think the problem is in your controller: your model rules are for multiple file upload and your form field too, but in the controller you set $model->file as a single UploadedFile instance. That is why your validation does not work. I can't give your advice (to change controller or model rule) because I do not clearly understand what are you doing here. It looks like you are creating multiple models from a single file upload field...