Reputation: 135
find All Models like this:
$models=Termin::model()->findAll(
array("condition"=>"status = 3"));
and than set new status with foreach:
foreach($models as $data) {
$data->status=1;
if($data->save())
{
echo 'saved';
}
}
but nothing happens ;(
Upvotes: 1
Views: 392
Reputation: 1579
Correction:
From Yii 1.1 onwards you can use save() for both update and save operations. CActiveRecord (your model's parent class) automatically determines if the current model ($data
in your case) is a fresh record or it was retrieved from a db (with $data->isNewRecord
property). If the record is fresh, CActiveRecord
class will automatically use insert() method and if it was retrieved from an existing recordset it will switch to update().
Your question: save() method (from CActiveRecord parent class) have two optional parameters. One to run validations (as set in your model rules) before actually sending to the db handler for saving, and the other to specify which attributes you want to save. By default this validation is set to true
- meaning: plain $data->save()
method will run all your model level validations. If the validations fail, there would not be any attempt at writing the record, but instead will add error details to the model. You can fetch these errors by calling $data->getErrors()
method on the model. (Note that getErrors() is from yet another parent class CModel)
If you call $data->save(false)
, model validations [defined in your model's rules()
] will not be run and the record will be passed on for the db handler for writing. This will come back with a success (or an exception, if there were any errors at the db level - e.g. foreign key / unique / other).
Hence, I would refactor your code as follows:
foreach($models as $data) {
$data->status=1;
try { // try catch block to capture db level mishaps
if ($data->save(true)) { // run model validations and if success
echo 'saved';
} else { // model validations failed
// Debug with var_dump($data->getErrors()) or Yii's CVarDumper class
// And/Or Display error message to user
}
} catch (CException $ex) { // This will catch any errors thrown during db write
// Debug with var_dump($ex)
// And/Or Display error message to user
}
}
Upvotes: 1
Reputation: 135
Found the Solution by my own.
In yii 1.1 its update() instead of save(). In yii 2 you can always use save() i thought!
Upvotes: 0