I am trying to work with cakephp virtualFields in cakephp 1.3. My sql query is as follows but I need day_index (my virtual fields) to be 'DAYOFWEEK(start_date)'.
I need to rewrite a query
$data = $this->Calendar->query("SELECT *, DAYOFWEEK(start_date) as day_index, TIME(start_time) as time
FROM calendars WHERE calendar_category_id =$cal ORDER BY day_index, time");
into this format:
$sqlConditions = array("Calendar.calendar_category_id"=>$cal);
$sqlOrderBy = array("Calendar.day_index", "Calendar.time asc");
$sqlParams = array('conditions'=>$sqlConditions,'order'=>$sqlOrderBy);
$data = $this->Calendar->find('all',$sqlParams);
$this->set('data',$data);
So I'm not sure how to/where to put or declare the virtual field.
$fields = $this->Calendar->virtualFields['day_index'].'AS 'DAYOFWEEK(start_date)';
Found 2 ways to do this, not sure if one is better than the other.
controller edit only method
$sqlFields = array("DAYOFWEEK(Calendar.start_date) as day_index",
"TIME(Calendar.start_time) as time",
"Calendar.start_date",
"Calendar.calendar_category_id",
"Calendar.start_time");
$sqlConditions = array("Calendar.calendar_category_id"=>$cal);
$sqlOrderBy = array("Calendar.day_index, Calendar.time asc");
$sqlParams = array('fields'=>$sqlFields,'conditions'=>$sqlConditions,'order'=>$sqlOrderBy);
$data = $this->Calendar->find('all',$sqlParams);
return $data;
exit();
model method with edits to controller based on this method
Model >
var $virtualFields = array(
'day_index' => "DAYOFWEEK(Calendar.start_date)",
'time' => "TIME(Calendar.start_time)"
);
var $displayIndex = 'day_index';
var $displayTime = 'time';
Controller >
$sqlConditions = array("Calendar.calendar_category_id"=>$cal);
$sqlOrderBy = array("Calendar.day_index, Calendar.time asc");
$sqlParams = array('conditions'=>$sqlConditions,'order'=>$sqlOrderBy);
$data = $this->Calendar->find('all',$sqlParams);
return $data;
exit();
Related
Hi first of all I should tell you that English is not my first language so excuse any misunderstandings. What I'm trying here is to access to the "donors" table data using the foreign key in the "packets" table and I need to get that data in the controller to use. I refer PacketID in my view and in the staff controller I need to get the specific DonorMobile and DonorName to send an SMS to that donor. I have tried creating multiple model functions but didn't work. Can it be done by that way or is there any other way? TIA!
Screenshots of donors and packets tables
donors table and
packets table
Staff controller - I know you can't access data like $donorData->DonorID in the controller
public function markAsUsed($packet)
{
$this->load->Model('Donor_Model');
$donorData = $this->Donor_Model->getDonors($packet);
$this->load->Model('Donor_Model');
$data = $this->Donor_Model->markAsUsed($donorData->DonorID);
$sid = 'twilio sid';
$token = 'twilio token';
$donorMobile = '+94' . $donorData->DonorMobile;
$twilioNumber = 'twilio number';
$client = new Twilio\Rest\Client($sid, $token);
$message = $client->messages->create(
$donorMobile, array(
'from' => $twilioNumber,
'body' => 'Thank you ' . $donorData->DonorName . ' for your blood donation. Your donation has just saved a life.'
)
);
if ($message->sid) {
$this->load->Model('Donor_Model');
$this->Donor_Model->changeStatus($data->isAvailable);
redirect('staff/viewpackets');
}
}
Model
function getDonors($packet) {
$data = $this->db->get_where('packets', array('PacketID' => $packet));
return $data->row();
}
function markAsUsed($donor)
{
$data = $this->db->get_where('donors', array('DonorID' => $donor));
return $data->row();
}
function changeStatus($packet)
{
$data = array(
'isAvailable' => False,
);
return $this->db->update('packets', $data, ['PacketID' => $packet]);
}
What you did in the answer is not advisable, using loops to fetch from tables will slow the system by large when you have large datasets. What was expected is to use JOIN queries to join the donors and packets tables as shown below:
$this->db->select('donors_table.DonorName,donors_table.DonorMobile,packets_table.*')->from('packets_table');
$this->db->join('donors_table','donors_table.DonorID=packets_table.DonorID');
$query = $this->db->get();
$result = $this->db->result();
Then you can iterate through each donor as below:
foreach($result as $row){
$donarName = $row->DonorName;
$donorMobile = $row->DonorMobile;
}
NB: It is always advisable to perform any fetch, insert, delete or update operations from the model, that is why Codeigniter is an MVC. Stop fetching data directly from database within Controllers.
Found the answer! You can do this only using the controller.
$packetData = $this->db->get_where('packets', array('PacketID' => $packet));
foreach ($packetData->result() as $row) {
$donorID = $row->DonorID;
$packetDonatedDate = $row->DonatedDate;
}
$donorData = $this->db->get_where('donors', array('DonorID' => $donorID));
foreach ($donorData->result() as $row) {
$donarName = $row->DonorName;
$donorMobile = $row->DonorMobile;
}
I'm having some trouble here V_shop_menu $order_uuid is not populating. Now I'm guessing this is because its yet to be created this is done further below. The problem I have is there are 2 statements here doing inserts to tables but they both rely on each other.
I have a bit of chicken and egg situation as I need $shop_menu_uuid from the top area to complete the bottom insert. I was led to believe that as they are in the same public function it would just work but this is not the case.
What do I need to do to make this happen?
Thanks!
public function add_shopmenu(){
$postData = $this->input->post();
$condition['conditions'][] = "site_name ='".$this->sessionInfo['site']."'";
$site = $this->frontguide_Model->selectSingleRow("t_place",$condition);
$site_uuid = $site['site_uuid'];
unset($condition);
$condition['conditions'][] = "site_uuid ='".$site['site_uuid']."'";
$condition['conditions'][] = "shop_menu_name ='".$postData['shop_menu_name']."'";
$shopmenu_name = $this->frontguide_Model->selectData("v_shop_menus",$condition);
unset($condition);
$condition['conditions'][] = "site_uuid ='".$site['site_uuid']."'";
$shopmenus = $this->frontguide_Model->selectData("v_shop_menus",$condition);
$shop_menu_enabled = (isset($postData['shop_menu_enabled']))?$postData['shop_menu_enabled']:"false";
$shop_menu_uuid = $this->frontguide_functions->uuid();
$v_shop_menu= array(
"shop_menu_uuid" =>$shop_menu_uuid,
"site_uuid" =>$site_uuid,
"order_uuid" =>$order_uuid,
"shop_menu_extension" =>$shop_menu_extension,
"shop_menu_name" =>$postData['shop_menu_name'],
"shop_menu_greet_long" =>$postData['shop_menu_greet_long'],
"shop_menu_greet_short" =>$postData['shop_menu_greet_short'],
"shop_menu_timeout" =>$postData['shop_menu_timeout'],
"shop_menu_enabled" => $shop_menu_enabled,
"shop_menu_cid_prefix"=>$postData['shop_menu_cid_prefix']
);
log_message('debug',print_r($v_shop_menu,TRUE));
$vgu_response = $this->frontguide_Model->insert("v_shop_menus",$v_shop_menu);
$shop_menu_option_digits = $postData['shop_menu_option_digits'];
$shop_menu_option_order = $postData['shop_menu_option_order'];
$shop_menu_option_description = $postData['shop_menu_option_description'];
$shop_menu_option_param = $postData['shop_menu_option_param'];
for($i=0;$i<count($shop_menu_option_digits);$i++){
$option = array();
$option['shop_menu_option_digits'] = $shop_menu_option_digits[$i];
$option['shop_menu_option_order'] = $shop_menu_option_order[$i];
$option['shop_menu_option_description'] = $shop_menu_option_description[$i];
$option['shop_menu_option_param'] = $shop_menu_option_param[$i];
$shop_menu_option_uuid= $this->frontguide_functions->uuid();
$option['shop_menu_option_uuid'] = $shop_menu_option_uuid;
$option['shop_menu_uuid'] = $shop_menu_uuid;
$option['site_uuid'] = $site_uuid;
$vgu_response = $this->frontguide_Model->insert("v_shop_menu_options",$option);
}
$order_uuid = $this->frontguide_functions->uuid();
$order_data = array(
"site_uuid"=>$site_uuid,
"order_uuid"=>$order_uuid,
“offer_uuid" => "a6788e9b-67bc-bd1b-df59-ggg5d51289ab",
"order_context"=>$site['site_name'],
"order_name" =>$postData['shop_menu_name'],
"order_number" =>$shop_menu_extension,
"order_continue" =>'true',
"order_order" =>'333',
"order_enabled" =>"true",
);
$v_orders = $this->frontguide_Model->insert("v_orders",$order_data);
Now I'm guessing this is because its yet to be created this is done
further below.
Yes you are right.
It is quite simple.
Insert v_shop_menus data without $order_uuid .
after inserting in v_orders, get the $order_uuid and update the v_shop_menus using $shop_menu_uuid.
I am a student who learns CodeIgniter, I have a school assignment about the database, I create a project, and run query in my model just like this.
class Send_model extends CI_Model{
function hello(){ $table = $this->db->query("SELECT * FROM (`tbl1`) LEFT JOIN `tbl2` ON `tbl2`.`id` = `tbl1`.`child_id` LEFT JOIN `tbl3` ON `tbl3`.`id` = `tbl1`.`child_id` ");
foreach($table->result() as $row){
$modbus[]= $row->modbus;
$data []= $row->data;
$alert[]= $row->alert;
};
$param0 = '&'.$modbus[0].'='.$data[0].':'.$alert[0];
$param1 = '&'.$modbus[1].'='.$data[1].':'.$alert[1];
$param2 = '&'.$modbus[2].'='.$data[2].':'.$alert[2];
$param3 = '&'.$modbus[3].'='.$data[3].':'.$alert[3];
$param4 = '&'.$modbus[4].'='.$data[4].':'.$alert[4];
$param5 = '&'.$modbus[5].'='.$data[5].':'.$alert[5];
$param6 = '&'.$modbus[6].'='.$data[6].':'.$alert[6];
$param7 = '&'.$modbus[7].'='.$data[7].':'.$alert[7];
$param8 = '&'.$modbus[8].'='.$data[8].':'.$alert[8];
$param9 = '&'.$modbus[9].'='.$data[9].':'.$alert[9];
$param10 = '&'.$modbus[10].'='.$data[10].':'.$alert[10];
$param11= '&'.$modbus[11].'='.$data[11].':'.$alert[11];
$param12 = '&'.$modbus[12].'='.$data[12].':'.$alert[12];
$param13 = '&'.$modbus[13].'='.$data[13].':'.$alert[13];
$param14 = '&'.$modbus[14].'='.$data[14].':'.$alert[14];
$param15 = '&'.$modbus[15].'='.$data[15].':'.$alert[15];
$param16 = '&'.$modbus[16].'='.$data[16].':'.$alert[16];
$param17 = '&'.$modbus[17].'='.$data[17].':'.$alert[17];
$param18 = '&'.$modbus[18].'='.$data[18].':'.$alert[18];
$sent = $param0.$param1.$param3.$param4.$param5.$param6.$param7.$param8.$param9.$param10.$param11.$param12.$param13.$param13.$param14.$param15.$param16.$param17;
return $sent;
}
my controller just like this
class Send extend CI_Controller{
function data ()
{
$this->load->model('send_model');
$send = $this->model->send_model->hello();
echo $sent;
}
}
i have a problem,if tbl1 add data then i have to write adding code to my script
can anyone help me to simplify this code?
It is because you're hard-coding to send only 19 rows of data by creating 19 $param variables. In a dynamic condition, you may have an empty record-set or hundreds of records. Modify the structure of your foreach loop to the following:
$param = array();
foreach($table->result() as $row){
$param[] = '&'.$row->modbus.'='.$row->data.':'.$row->alert;
}
return $param;
Hope it answers your question.
I am new to yii. I've created a custom in button in CGridView that has a class of CButtonColumn. I'm just wondering how can I pass parameters that I can add to my php function in my model.
This is my custom button in the table
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
'click'=>$model->approveRegistrants("$user_id, $category", array("id"=>$data->user_id , "category"=>$data->category),
)
)
)
and this is my function is
public function approveRegistrants($user_id, $category){
$db = new PDO('mysql:host=localhost; dbname=secret; charset=utf8', 'Andy', '*****');
$getCounter = "SELECT registrants FROM counter order by registrants desc limit 1;";
$bool = false;
$show = '0';
do{
$result = $db->query($getCounter);
// $registrants = $db->query($getCounter);
// $result->setFetchMode(PDO::FETCH_ASSOC);
// $registrants = '1';
foreach ($result as $value){
$registrants = $value['registrants'];
echo 'hello'.$registrants.'</br>';
}
// $registrants = $result['registrants'];
// print_r($registrants);
$max_registrants = '3400';
if($max_registrants > $registrants){
// pdo that will use $updateCounterByOne
$updateCounterByOne = "UPDATE counter set registrants = registrants + 1 WHERE registrants = ". $registrants .";";
$updateCounter = $db->prepare($updateCounterByOne);
$updateCounter->execute();
// return affected rows
$returnAffectedRows = $updateCounter->rowCount();
$bool = true;
// break;
}
else{
echo "No more slot Available";
// break;
}
}while($returnAffectedRows == '0');
if($bool = true){
//sql syntax
$selectApprovedUser = "SELECT user_id FROM registrants WHERE user_id = '". $user_id ."';";
//pdo that will use $selectApprovedUser
$updateApprovedUser = "UPDATE registrants set approved = 'YES' where user_id = ". $selectApprovedUser .";";
$updateApproved = $db->prepare($updateApprovedUser);
$updateApproved->execute();
//pdo that will use $insertApprovedUser
$insertApprovedUser = "INSERT INTO approved_registrants (user_id, category, approved_date) VALUES ('".$user_id."', '".$category."', 'curdate()');";
$insertApproved = $db->prepare($insertApprovedUser);
$insertApproved->execute();
//execute trial
$selectSomething = "SELECT registrants from counter where tandem = '0'";
$doSelect = $db->prepare($selectSomething);
$doSelect->execute();
$hello = $doSelect->fetchAll();
echo $hello[0]['registrants'];
}
}
your issue is that you are bypassing the controller fully here.
buttons column is configured with the following parameters
'buttonID' => array(
'label'=>'...', // text label of the button
'url'=>'...', // a PHP expression for generating the URL of the button
'imageUrl'=>'...', // image URL of the button. If not set or false, a text link is used
'options'=>array(...), // HTML options for the button tag
'click'=>'...', // a JS function to be invoked when the button is clicked
'visible'=>'...', // a PHP expression for determining whether the button is visible
)
See CButtonColumn for details.
As you can see click has to be a js function that will be called on clicking the button. You can rewrite your button like this
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
// Alternative -1 Url Method -> will cause page to change to approve/id
'url'=>'array("approve","id"=>$data->id)',
// Alternative -2 Js method -> use 1,2 not both
'click'=>'js:approve()',
)
)
)
in your CGridView configuration you add
array(
....
'id'=>'gridViewID', //Unique ID for grid view
'rowHtmlOptionsExpression'=> 'array("id"=>$data->id)',
)
so that each row has the unique ID, ( you can do the same to a button, but it slightly more difficult as $data is not available there)
in your js function you can do this.
<script type="text/javascript">
function approve(){
id = $(this).parent().parent().attr("id");
<?php echo CHtml::ajax(array( // You also can directly write your ajax
'url'=>array('approve'),
'type'=>'GET',
'dataType'=>'json',
'data'=>array('id'=>'js:id'),
'success'=>'js:function(json){
$.fn.yiiGridView.update("gridViewID",{});
// this will refresh the view, you do some other logic here like a confirmation box etc
}'
));?>
}
</script>
Finally your approve action
class YourController extend CController {
......
public function actionApprove(){
id = Yii::app()->request->getQuery('id');
$dataModel = MyModel::model()->findByPk($id); // This is the model has the $user_id, and $category
....
$OtherModel->approve($dataModel->user_id,$dataModel->category) // if approve is in the same model you can self reference the values of category and user_id directly no need to pass as parameters.
// Do some logic based on returned value of $otherModel->approve()
// return the values from the approve() function and echo from here if required back to the view, directly echoing output makes it difficult to debug which function and where values are coming from .
Yii::app()->end();
}
Can someone give me a hint what I am doing wrong?
public function getPaymentSumByTypeAndProject($project_id,$type) {
$type = (int) $type;
$project_id = (int) $project_id;
$rowset = $this->tableGateway->select(array('total_amount' => new Expression('SUM(payment.amount)')))->where(array('type' => $type, 'project_id' => $project_id));
$row = $rowset->toArray();
if (!$row) {
throw new \Exception("Busted :/");
}
return $rowset;
}
I want to make the same query:
SELECT SUM(amount) FROM payment WHERE type='$type' AND project_id ='$project_id';
Edit:
I made small progress, i have figured out how to sum whole column
public function getPaymentSumByTypeAndProject($project_id, $type) {
$type = (int) $type;
$project_id = (int) $project_id;
$resultSet = $this->tableGateway->select(function (Select $select) {
$select->columns(array(new \Zend\Db\Sql\Expression('SUM(amount) as amount')))->where('type="0"');
});
return $resultSet;
Maybe someone could help me to figure out how to add condition: "WHERE type='$type' AND project_id='$project_id'" ?
I know this is an old question, but I came across it and figured I'd throw in my two cents:
public function getPaymentSumByTypeAndProject($project_id, $type) {
// This TableGateway is already setup for the table 'payment'
// So we can skip the ->from('payment')
$sql = $this->tableGateway->getSql();
// We'll follow the regular order of SQL ( SELECT, FROM, WHERE )
// So the query is easier to understand
$select = $sql->select()
// Use an alias as key in the columns array instead of
// in the expression itself
->columns(array('amount' => new \Zend\Db\Sql\Expression('SUM(amount)')))
// Type casting the variables as integer can take place
// here ( it even tells us a little about the table structure )
->where(array('type' => (int)$type, 'project_id' => (int)$project_id));
// Use selectWith as a shortcut to get a resultSet for the above select
return $this->tableGateway->selectWith($select);
}
Also, an adapter can be retrieved from a table gateway like this:
$adapter = $this->tableGateway->getAdapter();
But you don't really need it anymore when you select using the above mentioned method.
Ok now this is working, tell me is this how it;s should be done?
public function getPaymentSumByTypeAndProject($project_id, $type) {
$type = (int) $type;
$project_id = (int) $project_id;
$adapter = $this->tableGateway->adapter;
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('payment');
$select->where(array('type'=>$type,'project_id'=>$project_id));
$select->columns(array(new \Zend\Db\Sql\Expression('SUM(amount) as amount')));
$selectString = $sql->getSqlStringForSqlObject($select);
$resultSet = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
return $resultSet;
}
use This one
$select = $this->getSql()->select()
->columns(array('amount' => new \Zend\Db\Sql\Expression('SUM(amount)')))
->where("type ='$type'")
->where("project_id ='$project_id'");
$resultSet = $this->selectWith($select);
$row = $resultSet->current();
// echo $select->getSqlString();die; //check query use this line
if(!$row){
return False;
}
return $row->amount;
try to make like that instead of (int) $type
intval($type);
and
intval($project_id);
and in your sql
change your variables to
'".$type."'
AND
'".$project_id."'