I have a function in my Model which is passed a single value and in which I have a query which is giving me two results.
public static function updImgtbl($id)
{
$total_images = 0;
$images_uploaded = 0;
$sqlquery = "SELECT SUM(CASE WHEN ims.`installation_id` = $id THEN 1 ELSE 0 END) AS total_images,
SUM(CASE WHEN ims.`image_upload_flag` = 1 AND ims.`installation_id` = $id THEN 1 ELSE 0 END) AS images_uploaded
FROM `installation_images_site` ims
INNER JOIN `installations` ins ON ins.`id` = ims.`installation_id`
WHERE (ims.`image_upload_flag` = 1 AND ims.`installation_id` = $id)
OR (ims.`installation_id` = $id)
GROUP BY ims.`installation_id`";
$pt = Yii::$app->db->createCommand($sqlquery)->queryAll();
foreach ($pt as $val)
{
$total_images= $val['total_images'];
$images_uploaded = $val['images_uploaded'];
}
return ["total_images" => $total_images, "images_uploaded"=>$images_uploaded];
}
This function is called from an API
$response = Installations::updImgtbl($install_id);
print_r($response);
exit();
The response is below
Array
(
[total_images] => 4
[images_uploaded] => 1
)
But I want to get these values in a variable in my API. How can I achieve it?
You can simply:
list($total_images, $images_uploaded) = array_values($response);
Then, you have total_images value in $total_images variable and images_uploaded in $images_uploaded variable.
I mean:
list($total_images, $images_uploaded) = Installations::updImgtbl($install_id);
echo $total_images; // 4
echo $images_uploaded; // 1
You can read more about list in official doc.
Another way is using extract() function. For example:
$response = Installations::updImgtbl($install_id);
extract($response);
echo $total_images; // 4
echo $images_uploaded; // 1
Related
I want to execute this query in a foreach loop to use the table in the elemant orWhere Requette (depending on the number of array elements).
foreach ( $mesDeparts as $mesDepart)
{
$holidays_rh_test = holidaystate::find()
->leftJoin('holidays', '`holidays`.`id` = `holidayState`.`holiday_id`')
->leftJoin('user', '`user`.`id` = `holidays`.`user_id`')
->leftJoin('space_membership', '`user`.`id` = `space_membership`.`user_id`')
// ->where(['holidayState.user_id'=>0, 'holidayState.user_position_id'=>0, 'holidayState.stat'=>'2'])
->where(['space_membership.space_id'=>$mesDepart->space_id])
->andFilterWhere(['or',['holidayState.user_id'=>Yii::$app->user->id,'holidayState.user_position_id'=>$user_position->id ],['holidayState.user_id'=>0, 'holidayState.user_position_id'=>0, 'holidayState.stat'=>'2']])
->orderBy('holiday_id DESC')
->all();
}
You are repeating the query
You should build an array and use in clause
foreach ( $mesDeparts as $key =>$mesDepart) {
$my_array[$key] = $mesDepart->space_id;
}
$holidays_rh_test = holidaystate::find()
->leftJoin('holidays', '`holidays`.`id` = `holidayState`.`holiday_id`')
->leftJoin('user', '`user`.`id` = `holidays`.`user_id`')
->leftJoin('space_membership', '`user`.`id` = `space_membership`.`user_id`')
->andFiilterWhere(['in', 'space_membership.space_id', $my_array])
->orderBy('holiday_id DESC')
->all();
I have a function in my model EmployeePersonal.php named get_employee_details which accepts some parameter and return the employees details. This function is used my many controllers and I prefer not to change this function.
Now I have a function view in my EmployeePersonalsController.php which outputs approx 4000 results. eg
$res = $this->EmployeePersonal->get_employee_details(
$office_id = $office_id,
$epf_no = $epf_no,
$employee_personal_id = $employee_personal_id,
$status = $status,
$permanent_district_id = $permanent_district_id,
$present_district_id = $present_district_id,
$department_id = $department_id,
$designation_id = $designation_id,
$category_id = $category_id,
$gender_type = $gender_type,
$offset = $offset,
$size = $size
);
I need to put a pagination in my view function , is there any way how can I put the $paginate here ?
I'm trying to bind some arguments to my GQL query string.
Everything's fine when I run the query without binding anything:
$result = $DB->query_entities("SELECT * FROM kind WHERE fieldName = 4
LIMIT 1");
But I don't know how to bind some arguments. This is how I'm trying to do so:
function query_entities($query_string, $args=[]){
$gql_query = new Google_Service_Datastore_GqlQuery();
$gql_query->setQueryString($query_string);
$gql_query->setAllowLiteral(true);
if( !empty($args) ){
$binding_args = [];
foreach ($args as $key => $value) {
$binding_value = new Google_Service_Datastore_Value();
$binding_value->setIntegerValue($value);
$arg = new Google_Service_Datastore_GqlQueryArg();
$arg->setName($key);
$arg->setValue($binding_value);
$binding_args[] = $arg;
}
$gql_query->setNameArgs($binding_args);
}
$req = new Google_Service_Datastore_RunQueryRequest();
$req->setGqlQuery($gql_query);
return $this->dataset->runQuery($this->dataset_id, $req, []);
}
$exampleValue = 4;
$result = $DB->query_entities("SELECT * FROM kind WHERE fieldName = :fieldName LIMIT 1", ["fieldName" => $exampleValue]);
Or:
function query_entities($query_string, $args=[]){
$gql_query = new Google_Service_Datastore_GqlQuery();
$gql_query->setQueryString($query_string);
$gql_query->setAllowLiteral(true);
if( !empty($args) ){
$binding_args = [];
foreach ($args as $value) {
$binding_value = new Google_Service_Datastore_Value();
$binding_value->setIntegerValue($value);
$arg = new Google_Service_Datastore_GqlQueryArg();
$arg->setValue($binding_value);
$binding_args[] = $arg;
}
$gql_query->setNumberArgs($binding_args);
}
$req = new Google_Service_Datastore_RunQueryRequest();
$req->setGqlQuery($gql_query);
return $this->dataset->runQuery($this->dataset_id, $req, []);
}
$exampleValue = 4;
$result = $DB->query_entities("SELECT * FROM kind WHERE fieldName = :1 LIMIT 1", [$exampleValue]);
This is what I get:
'Error calling POST https://www.googleapis.com/datastore/v1beta2/datasets/age-of-deployment/runQuery: (400) Lexical error at line 1, column 52. Encountered: ":" (58), after : ""' in ...
Cloud Datastore GQL and Python GQL (App Engine) handle argument binding slightly differently.
In this case, you need to use a # instead of a :, for instance:
SELECT * FROM kind WHERE fieldName = #fieldName LIMIT 1
or
SELECT * FROM kind WHERE fieldName = #1 LIMIT 1
Here's the reference documentation for argument binding in Cloud Datastore GQL.
I have a similar problem that the function only return the first loop data.
The result should be 2 loops and each loop has rows data.
For example, The first loop is A and has 5 rows data and second loop is B and has 5 rows.
The return value only A with 5 rows, it sould be 10 rows. 5 rows A + 5 rows B.
How is the code should be?
This function in model is bellow
function getDataForm($data_search)
{
$i=0;
if(!empty($data_search['arr_idacl']))
{
foreach($data_search['arr_idacl'] as $idx => $val)
{
if(!empty($operatingHour))
{
$sql = "SELECT be_acl_resources.description as description,DATE_FORMAT(tbl_camera_detail.start_time,'%d %M %Y ') as datadate, SUM(IF(tbl_consolid_detail.operation = 'plus' AND tbl_consolid_detail.direction = 'IN',tbl_camera_detail.enters,0))+SUM(IF(tbl_consolid_detail.operation = 'minus' AND tbl_consolid_detail.direction = 'IN',tbl_camera_detail.enters*(-1),0))+SUM(IF(tbl_consolid_detail.operation = 'plus' AND tbl_consolid_detail.direction = 'OUT',tbl_camera_detail.exits,0))+SUM(IF(tbl_consolid_detail.operation = 'minus' AND tbl_consolid_detail.direction = 'OUT',tbl_camera_detail.exits*(-1),0)) as total_enter FROM tbl_consolid JOIN tbl_consolid_detail ON tbl_consolid.id = tbl_consolid_detail.consolid_id JOIN tbl_config_data ON tbl_consolid_detail.config_data_id = tbl_config_data.id JOIN tbl_camera ON tbl_config_data.id_acl = tbl_camera.id_acl JOIN tbl_camera_detail ON tbl_camera.id = tbl_camera_detail.camera_id JOIN be_acl_resources ON tbl_consolid.id_acl = be_acl_resources.id WHERE tbl_camera.date >= '".$data_search['start_date']."' AND date_format(tbl_camera_detail.start_time, '%H, %i %S') >= '".$startOpratingHour."' AND date_format(tbl_camera_detail.start_time, '%H, %i %S') <= '".$operatingHour['finish_time']."' AND tbl_camera.date <= '".$data_search['end_date']."' AND tbl_consolid.id_acl = '".$val."' GROUP BY tbl_camera.date";
echo $sql;
$query = $this->db->query($sql);
$result_data[] = $query->result();
//return $result;
}
$i++;
}
return $result_data;
}
}
Declare $result_data = array(); just before if(!empty($data_search['arr_idacl'])) condition.
Replace $result_data[] = $query->result(); with $result_data[$i] = $query->result();
Update:
Just close to the answer. :) Try this:
Replace $result_data[] = $query->result(); with $result_data[$i][] = $query->result();
When I try to run app/users/initdb, I'm getting warning 512 and i'm not able to populate the aros_acos table. Does anyone know on i'm doing wrong:
Warning (512): DbAcl::allow() - Invalid node [CORE\cake\libs\controller\components\acl.php, line 361]Code | Context
if ($perms == false) {
trigger_error(__('DbAcl::allow() - Invalid node', true), E_USER_WARNING);$aro = Group
Group::$name = "Group"
Group::$validate = array
Group::$hasMany = array
Group::$actsAs = array
Group::$useDbConfig = "default"
Group::$useTable = "groups"
Group::$displayField = "name"
Group::$id = 7
Group::$data = array
Group::$table = "groups"
Group::$primaryKey = "id"
Group::$_schema = array
Group::$validationErrors = array
Group::$tablePrefix = ""
Group::$alias = "Group"
Group::$tableToModel = array
Group::$logTransactions = false
Group::$cacheQueries = false
Group::$belongsTo = array
Group::$hasOne = array
Group::$hasAndBelongsToMany = array
Group::$Behaviors = BehaviorCollection object
Group::$whitelist = array
Group::$cacheSources = true
Group::$findQueryType = NULL
Group::$recursive = 1
Group::$order = NULL
Group::$virtualFields = array
Group::$__associationKeys = array
Group::$__associations = array
Group::$__backAssociation = array
Group::$__insertID = NULL
Group::$__numRows = NULL
Group::$__affectedRows = NULL
Group::$_findMethods = array
Group::$User = User object
Group::$Aro = Aro object
$aco = "controllers"
$actions = "*"
$value = 1
$perms = false
$permKeys = array(
"_create",
"_read",
"_update",
"_delete"
)
$save = array()DbAcl::allow() - CORE\cake\libs\controller\components\acl.php, line 361
AclComponent::allow() - CORE\cake\libs\controller\components\acl.php, line 106
UsersController::initdb() - APP\controllers\users_controller.php, line 82
Dispatcher::_invoke() - CORE\cake\dispatcher.php, line 204
Dispatcher::dispatch() - CORE\cake\dispatcher.php, line 171
[main] - APP\webroot\index.php, line 83
The following is my users_controller.php
class UsersController extends appController{
var $name = 'Users';
function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow(array('*'));
}
function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
function login(){
}
function logout(){
}
.........
function initdb(){
//gets reference of Group model and modify its id to be able to specify the ARO we wanted, this is due to how AclBehavior works. AclBehavior does not set the alias field in the aros table so we must use an object reference or an array to reference the ARO we want.
$group=& $this->User->Group;
//Allow admins to everything
$group->id=7;
$this->Acl->allow($group,'controllers');
//allow managers to posts and widgets
$group->id=8;
$this->Acl->deny($group,'controllers');
$this->Acl->allow($group,'controllers/Posts');
$this->Acl->allow($group, 'controllers/Widgets');
//allow users to only add and edit on posts and widgets
$group->id=9;
$this->Acl->deny($group,'controllers');
$this->Acl->allow($group,'controllers/Posts/add');
$this->Acl->allow($group,'controllers/Posts/edit');
$this->Acl->allow($group,'controllers/Widgets/add');
$this->Acl->allow($group,'controllers/Widgets/edit');
//we add an exit to avoid an ugly "missing views" error message
echo "all done";
exit;
}
any help is much appreciated. Thanks.