Here is my code:
$update_data = array('post_browe_count'=>new Zend_Db_Expr('post_browe_count+1'));
$rowaffected = $contentmodel->update_post('posts',$update_data,$id);
my class extend directly from Zend_Db_Table_Abstract,how can I solve it
Here i am giving you an example using products and incrementing a quantity field:
$table = 'products';
$data = array('prd_qnty' => new Zend_Db_Expr('product_qnty + 1'));
$where[] = $db->quoteInto('product_id = ?', $this->pr_id);
$db->update($table, $data, $where);
just try to do your query as above. so it will sure work for you.
let me know if i can help you more.
Related
I have a table, myTable, with a single column, myColumn, with a single row.
I want to change the value of myColumn in that first (and only) row.
I tried this, but nothing happens:
$myNewValue = 'foo';
$this->db->update('myColumn', $myNewValue);
What am I doing wrong?
Obviously it must have something to do with not specifying which table, but I don't know how to do that.
Codeigniter's update() needs to follow this syntax:
update([$table = ''[, $set = NULL[, $where = NULL[, $limit = NULL]]]])
Parameters:
$table (string) – Table name
$set (array) – An associative array of field/value pairs
$where (string) – The WHERE clause
$limit (int) – The LIMIT clause
so besides of adding the correct table name, you'd need to send update data as an array, using this approach:
$myNewValue = array('myColumn'=>'foo');
$this->db->update('myTable', $myNewValue);
Figured out how to do it:
$this->db->update('myTable', [
'myColumn' => $myNewValue,
]);
Try this method, it is my favorite format.
$where = array(
'column_id'=$id
);
$data = array(
'column_name'=$data
);
$this->db->update('table_name', $data,$where);
Inside my store function i have to search a name of a particular person, thus:
$person = DB::select("select p.* from persons p where concat_ws(', ' ,p.family_name,concat_ws(' ',concat_ws(' ',p.first_name,p.middle_name),p.third_name)) like ?", [$request['person_name']]);
If this person exist i have to update the person and this one works:
Person::where('id', $person[0]->id)->update(['status' => 'Active']);
but not this one:
$person[0]->status = 'Active';
$pArray = json_decode(json_encode($person[0]), true);
$per = new Person($pArray);
$per->update();
Since you have already created a new model instance, you would need to call the save() method.
$per = new Person($pArray);
$per->save();
Or, you can use update() to pass data into an existing model. But first, you need to retrieve the model you want to update.
$per = Person::find($pArray['id']);
$per->update($pArray);
Use your search query instead of mine. I think this will help you.
$result = User::where('id', $userId)->first();
$result->name = 'xyz';
$result->update();
For update data in laravel using model you need to pass where condition in it.
Sample example
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
Hope this helps you!
I want to get the data form database table and create a new row in another table.
Which 1 PO have many PoProducts.
$_getPO = Order::find($id);
$_getPOProducts= OrderProducts::where('order_id', $id)->get();
$order_no = $_getPO->order_no;
$eta = $_getPO->eta;
$_Order = new DeliveryOrders();
$_Order->order_no = $order_no;
$_Order->eta = $eta;
$_Order->save();
$POProduct = array();
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[] = new DeliveryOrderProducts();
$POProduct[] = $_getPOProduct->order_id;
$POProduct[] = $_getPOProduct->item_id;
$POProduct[] = $_getPOProduct->qty;
$POProduct->save();
}
But, this output an error.
Call to a member function save() on array
Please help me. Thanks.
If you wish to copy records from one table to another or just duplicate a record in the same table you could simply use the repliacate() method.
$user = User::findOrFail($id);
// replicate (duplicate) the data
$staff = $user->replicate();
// make into array for mass assign.
//make sure you activate $guarded in your Staff model
$staff = $staff->toArray();
Staff::firstOrCreate($staff);
Note: in case you're only duplicating on the same table replace Staff with User on this example.
You are trying to run the save method on the array but what you want is to use it on the array index instead.
Change your foreach to this and it should work (assuming columns are the same).
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = new DeliveryOrderProducts();
$POProduct[$i]->order_id = $_getPOProduct->order_id;
$POProduct[$i]->item_id = $_getPOProduct->item_id;
$POProduct[$i]->qty = $_getPOProduct->qty;
$POProduct[$i]->save();
}
You can shorten this by using forceCreate.
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = (new DeliveryOrderProducts())->forceCreate($_getPOProduct->only(['order_id', 'item_id', 'qty']));
}
Am trying to perform this query
$command = $connection->createCommand("
SELECT
tbl_checklist.report_val AS item
FROM tbl_checks
LEFT JOIN tbl_checklist ON tbl_checklist.id = tbl_checks.check_id
WHERE truck_id = ".$value->id."
"
);
$results = $command->queryAll();
THe above works but i would like to perform the same using models
So i have tried
$results = TblChecks::find()
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
How do i add the SELECT tbl_checklist.report_val AS item in the Model flow
you should try like this
$results = TblChecks::find()->select(["tbl_checklist.report_val AS item","tbl_checks.*"])
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
Try this way, I hope it will solve your issue.
$results = TblChecks::find()
->select[tbl_checklist.report_val AS item]
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
You should use select() function:
$results = TblChecks::find()
->select('tbl_checklist.report_val AS item')
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
And add property $item in your model.
I have following code to fetch data from a model.
$notifyModel = Notification::model()->findByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
Now I want to count the number of rows fetched.
Neither $notifyModel->count() work nor count($notifyModel).
It is very simple but googling did not help.
$notifyModels = Notification::model()->findAllByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
$count = count($notifyModels);
Or
$count = Notification::model()->countByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
the right usage of count():
$userid = Yii::app()->user->uid;
$count = Notification::model()->count( 'user_id=:userid', array(':userid' => $userid));
Please see http://www.yiiframework.com/doc/api/1.1/CActiveRecord#count-detail
try this:
$userid = Yii::app()->user->uid;
$notifyModel = Notification::model()->count(
array('condition' => 'user_id=:userid',
'params'=>array(':userid' => $userid)
));
$count = Notification::model()->countByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
Since the questions title is about calling the count function in a model I'll add some for those beginners reading this :)
A function inside a model could look like this:
/**
* Count the number of rows which match the user ID
* #param int $uid The user ID
* #return int The number of found rows
*/
public function getCountByUserID($uid)
{
$count = $this->count(array(
'condition'=>'user_id = :uid',
'params'=>array(
':uid'=>$uid,
),
));
return $count;
}
simple ways:
$model = News::model()->findAll(); //returns AR objects
$count = count($model);
I think it is much faster than others
$userTable=User::model()->tableName();
$userid = Yii::app()->user->uid;
$criteria=new CDbCriteria();
$criteria->select=count(id);
$criteria->compare('user_id',$userid);
$count=Yii::app()->db->commandBuilder->createFindCommand($userTable,$criteria)->queryScalar();
That method is wrong!
You trying to get by selecting all rows from database, you load the server, but that's wrong way!
All you need to do :
$sql = "SELECT COUNT(*) FROM {{...table_name...}}";
$count = intval(Yii::app()->db
->createCommand($sql)
->queryScalar());
Or you can create function in your model:
Class User extends CActiveRecord
{
private $_total;
public function getTotalItems()
{
if( empty( $this->_total )) {
$this->_total = intval(Yii::app()->db
->createCommand($sql)->queryScalar());
}
return $this->_total;
}
}
then you can use this functions like this:
$totalItems = User::model()->totalItems;
or :
$model = User::model()->findByPk( $uid );
$totalItems = $model->totalItems;
or :
$model = new User;
$totalItems = $model->totalItems;
This is the most simple way to do that:
$count = Table::Model()
->count("field=:field", array("field" => $fildID));
echo $count;
I strongly recommend you to find count with SQL query else it will degrade your system performance.
There are three way to find out count with the SQL query itself in Yii 1 CActiveRecord, those are:
1. count() method
Finds the number of rows satisfying the specified query condition.
Example :
$count = Notification::model()->count('user_id'=> Yii::app()->user->uid);
2. countByAttributes() method (available since v1.1.4)
Finds the number of rows that have the specified attribute values.
Example :
$count = Notification::model()->countByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
3. countBySql() method
Finds the number of rows using the given SQL statement. This is equivalent to calling CDbCommand::queryScalar with the specified SQL statement and the parameters.
Example:
$count = Notification::model()
->countBySql("select *from notification where user_id=:userId",
array(':userId'=>Yii::app()->user->uid)
);
Don't use the following code, which will reduce system performance:
$notifyModels = Notification::model()->findAllByAttributes(array(
'user_id'=> Yii::app()->user->uid
));
$count = count($notifyModels);
Because, there are two function call to find the count
In my research, The easiest and Best Practice is like below.
$notifyModel = Notification::model()->count(array('user_id'=> Yii::app()->user->uid));