Yii Framework Forum: [EXTENSION] CSaveRelationsBehavior - Yii Framework Forum

Jump to content

  • (3 Pages)
  • +
  • 1
  • 2
  • 3
  • You cannot start a new topic
  • You cannot reply to this topic

[EXTENSION] CSaveRelationsBehavior CSaveRelationsBehavior Save HasMany and ManyMany relational active rec Rate Topic: ***** 1 Votes

#21 User is offline   Sander 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 169
  • Joined: 03-November 09
  • Location:Amsterdam, Netherlands

Posted 09 July 2010 - 02:57 AM

I'm not really sure what you mean with the 'flipped key definition'. Correct me if I'm wrong, but I thought Yii's MANY_MANY relations are supposed to work like this:

	public function relations() {
                return array(
                        'relation' => array(self::MANY_MANY, 'OtherModel', 'JoinTable(MY_PRIMARY_KEY, RELATED_PRIMARY_KEY)'),
                );
        }


That's the way I set it up, and that's the only way I get a proper result set back from Yii. As I said, if I change the key definition in the relation definition, it doesn't change the CDbException that gets thrown when I call the save() method on my model..
0

#22 User is offline   Juban 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 12-January 09
  • Location:Grenoble France

Posted 09 July 2010 - 07:44 AM

View PostSander, on 09 July 2010 - 02:57 AM, said:

As I said, if I change the key definition in the relation definition, it doesn't change the CDbException that gets thrown when I call the save() method on my model..


To clarify things a bit more, what is the exact exception you get in that case? Is it the same?
0

#23 User is offline   Sander 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 169
  • Joined: 03-November 09
  • Location:Amsterdam, Netherlands

Posted 09 July 2010 - 08:05 AM

Yeah, it's the same Exception wether I flip the keys or not:

Quote

CDbException

Description

Table "Perceel" does not have a column named "bedrijf_id".

Source File

/Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/db/schema/CDbCommandBuilder.php(544)
00532:                     }
00533:                     else
00534:                     {
00535:                         $conditions[]=$prefix.$column->rawName.'='.self::PARAM_PREFIX.$i;
00536:                         $values[self::PARAM_PREFIX.$i]=$value;
00537:                         $i++;
00538:                     }
00539:                 }
00540:                 else
00541:                     $conditions[]=$prefix.$column->rawName.' IS NULL';
00542:             }
00543:             else
00544:                 throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
00545:                     array('{table}'=>$table->name,'{column}'=>$name)));
00546:         }
00547:         $criteria->params=array_merge($values,$criteria->params);
00548:         if(isset($conditions[0]))
00549:         {
00550:             if($criteria->condition!='')
00551:                 $criteria->condition=implode(' AND ',$conditions).' AND ('.$criteria->condition.')';
00552:             else
00553:                 $criteria->condition=implode(' AND ',$conditions);
00554:         }
00555:         return $criteria;
00556:     }

Stack Trace
#0 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/db/ar/CActiveRecord.php(1327): CDbCommandBuilder->createColumnCriteria(Object(CDbTableSchema), Array, '', Array, ''t'.')
#1 /Users/sander/Sites/VROM/protected/components/CSaveRelationsBehavior.php(129): CActiveRecord->findByAttributes(Array)
#2 [internal function]: CSaveRelationsBehavior->setRelationRecords('percelen', Array)
#3 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/base/CComponent.php(261): call_user_func_array(Array, Array)
#4 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/db/ar/CActiveRecord.php(195): CComponent->__call('setRelationReco...', Array)
#5 [internal function]: CActiveRecord->__call('setRelationReco...', Array)
#6 /Users/sander/Sites/VROM/protected/models/Bedrijf.php(119): Bedrijf->setRelationRecords('percelen', Array)
#7 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/validators/CInlineValidator.php(39): Bedrijf->validatePerceel('perceel', Array)
#8 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/validators/CValidator.php(178): CInlineValidator->validateAttribute(Object(Bedrijf), 'perceel')
#9 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/base/CModel.php(150): CValidator->validate(Object(Bedrijf), NULL)
#10 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/db/ar/CActiveRecord.php(723): CModel->validate(NULL)
#11 /Users/sander/Sites/VROM/protected/controllers/BedrijfController.php(88): CActiveRecord->save()
#12 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/actions/CInlineAction.php(32): BedrijfController->actionUpdate()
#13 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/CController.php(300): CInlineAction->run()
#14 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/filters/CFilterChain.php(129): CController->runAction(Object(CInlineAction))
#15 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/filters/CFilter.php(41): CFilterChain->run()
#16 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/CController.php(1049): CFilter->filter(Object(CFilterChain))
#17 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/filters/CInlineFilter.php(59): CController->filterAccessControl(Object(CFilterChain))
#18 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/filters/CFilterChain.php(126): CInlineFilter->filter(Object(CFilterChain))
#19 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/CController.php(283): CFilterChain->run()
#20 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/CController.php(257): CController->runActionWithFilters(Object(CInlineAction), Array)
#21 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/CWebApplication.php(324): CController->run('update')
#22 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/web/CWebApplication.php(121): CWebApplication->runController('bedrijf/update')
#23 /Users/sander/Sites/Tools/yii-1.1.3.r2247/framework/base/CApplication.php(135): CWebApplication->processRequest()
#24 /Users/sander/Sites/VROM/debug.php(12): CApplication->run()
#25 {main}


0

#24 User is offline   Juban 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 12-January 09
  • Location:Grenoble France

Posted 09 July 2010 - 11:38 AM

View PostSander, on 09 July 2010 - 08:05 AM, said:

Yeah, it's the same Exception wether I flip the keys or not:

Hmm... To me, it makes no sense that it triggers the same error in both cases.
Anyway, while testing with no foreign keys set on the MANY_MANY table, I ran into an error while saving the data.
I'm writing some fixes about that and come back to you as soon as it's working fine.

Thank you for you help.

Alban.
0

#25 User is offline   cadju 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 5
  • Joined: 05-May 10

Posted 06 October 2010 - 06:54 PM

I've installed the demo application 11. Everithing works fine except when I try to update a library I get this error:"Property "LibraryBook." is not defined."

Help me please.

Thanks
0

#26 User is offline   bitmatix 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 162
  • Joined: 23-March 09

Posted 20 November 2010 - 06:52 AM

I have a problem with a MANY_MANY relation, where my relation table looks like this:


CREATE TABLE `CategoryRelation` (
  `idCategory` int(10) unsigned NOT NULL,
  `idCategoryRelation` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`idCategory`,`idCategoryRelation`),
  KEY `idCategoryRelation` (`idCategoryRelation`),
  CONSTRAINT `CategoryRelation_ibfk_1` FOREIGN KEY (`idCategory`) REFERENCES `Category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `CategoryRelation_ibfk_2` FOREIGN KEY (`idCategoryRelation`) REFERENCES `Category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8


the relation defined in my "Category" class looks like this:

'arrCategoryRelation' => array(self::MANY_MANY, 'Category', 'CategoryRelation(idCategory, idCategoryRelation)'),


the problem is that the only relations that would be save, are the one where the ids are identically, i.e.:

1-1
2-2
3-3

but not:

1-2
1-3
2-1
2-3
3-1
3-2

any suggestions?
1

#27 User is offline   micnie 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 3
  • Joined: 01-December 10

Posted 08 December 2010 - 04:47 AM

Hi All,

Warmest Regards.

I try to run the demo10, i getting error

CExceptionDescription Property "LibraryBook.0" is not defined.
Source File C:\inetpub\wwwroot\yii\framework\db\ar\CActiveRecord.php(126)


Could any one let me know what is going wrong. I'm using MSSQL Database.

Thank you.

Regards,
Micheale
0

#28 User is offline   fouss 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 385
  • Joined: 05-October 10
  • Location:Bamako Mali

Posted 17 December 2010 - 07:10 AM

Hi all,
I'm trying demo11 and I get this error when I try to add a book.
I'm using yii 1.1.4

thx

Quote

CException
Description
Property "LibraryBook." is not defined.

Source File
C:\wamp\www\yii\framework\db\ar\CActiveRecord.php(110)

00098: */
00099: public function __get($name)
00100: {
00101: if(isset($this->_attributes[$name]))
00102: return $this->_attributes[$name];
00103: else if(isset($this->getMetaData()->columns[$name]))
00104: return null;
00105: else if(isset($this->_related[$name]))
00106: return $this->_related[$name];
00107: else if(isset($this->getMetaData()->relations[$name]))
00108: return $this->getRelated($name);
00109: else
00110: return parent::__get($name);
00111: }
00112:
00113: /**
00114: * PHP setter magic method.
00115: * This method is overridden so that AR attributes can be accessed like properties.
00116: * @param string property name
00117: * @param mixed property value
00118: */
00119: public function __set($name,$value)
00120: {
00121: if($this->setAttribute($name,$value)===false)
00122: {
Stack Trace
#0 C:\wamp\www\yii\framework\db\ar\CActiveRecord.php(110): CComponent->__get('')
#1 C:\wamp\www\yii\framework\web\helpers\CHtml.php(1995): CActiveRecord->__get('')
#2 C:\wamp\www\yii\framework\web\helpers\CHtml.php(1743): CHtml::resolveValue(Object(LibraryBook), '[0]bookISBN')
#3 C:\wamp\www\yii\framework\web\helpers\CHtml.php(1181): CHtml::activeInputField('text', Object(LibraryBook), '[0]bookISBN', Array)
#4 C:\wamp\www\yii\framework\web\widgets\CAutoComplete.php(220): CHtml::activeTextField(Object(LibraryBook), '[0]bookISBN', Array)
#5 C:\wamp\www\yii\framework\web\CBaseController.php(140): CAutoComplete->init()
#6 C:\wamp\www\yii\framework\web\CBaseController.php(165): CBaseController->createWidget('CAutoComplete', Array)
#7 C:\wamp\www\csrbdemo11\protected\views\library\_form.php(59): CBaseController->widget('CAutoComplete', Array)
#8 C:\wamp\www\yii\framework\web\CBaseController.php(119): require('C:\wamp\www\csr...')
#9 C:\wamp\www\yii\framework\web\CBaseController.php(88): CBaseController->renderInternal('C:\wamp\www\csr...', Array, true)
#10 C:\wamp\www\yii\framework\web\CController.php(798): CBaseController->renderFile('C:\wamp\www\csr...', Array, true)
#11 C:\wamp\www\csrbdemo11\protected\views\library\create.php(15): CController->renderPartial('_form', Array)
#12 C:\wamp\www\yii\framework\web\CBaseController.php(119): require('C:\wamp\www\csr...')
#13 C:\wamp\www\yii\framework\web\CBaseController.php(88): CBaseController->renderInternal('C:\wamp\www\csr...', Array, true)
#14 C:\wamp\www\yii\framework\web\CController.php(798): CBaseController->renderFile('C:\wamp\www\csr...', Array, true)
#15 C:\wamp\www\yii\framework\web\CController.php(739): CController->renderPartial('create', Array, true)
#16 C:\wamp\www\csrbdemo11\protected\controllers\LibraryController.php(92): CController->render('create', Array)
#17 C:\wamp\www\yii\framework\web\actions\CInlineAction.php(50): LibraryController->actionCreate()
#18 C:\wamp\www\yii\framework\web\CController.php(300): CInlineAction->run()
#19 C:\wamp\www\yii\framework\web\filters\CFilterChain.php(133): CController->runAction(Object(CInlineAction))
#20 C:\wamp\www\yii\framework\web\filters\CFilter.php(41): CFilterChain->run()
#21 C:\wamp\www\yii\framework\web\CController.php(1049): CFilter->filter(Object(CFilterChain))
#22 C:\wamp\www\yii\framework\web\filters\CInlineFilter.php(59): CController->filterAccessControl(Object(CFilterChain))
#23 C:\wamp\www\yii\framework\web\filters\CFilterChain.php(130): CInlineFilter->filter(Object(CFilterChain))
#24 C:\wamp\www\yii\framework\web\CController.php(283): CFilterChain->run()
#25 C:\wamp\www\yii\framework\web\CController.php(257): CController->runActionWithFilters(Object(CInlineAction), Array)
#26 C:\wamp\www\yii\framework\web\CWebApplication.php(324): CController->run('create')
#27 C:\wamp\www\yii\framework\web\CWebApplication.php(121): CWebApplication->runController('library/create')
#28 C:\wamp\www\yii\framework\base\CApplication.php(135): CWebApplication->processRequest()
#29 C:\wamp\www\csrbdemo11\index.php(13): CApplication->run()
#30 {main}2010-12-17 12:09:54 Apache/2.2.11 (Win32) PHP/5.3.0 Yii Framework/1.1.4


Posted Image
0

#29 User is offline   Juban 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 12-January 09
  • Location:Grenoble France

Posted 18 December 2010 - 02:49 AM

Hi all,

I've been very busy lately and I wish you forgive me to give no answer to your previous messages.
Seems like the demos applications are buggy, specially the Yii 1.1 one.
I will try to fix that as soon as possible and publish a corrected version.

Thanks for you patience and support.

Regards.

Alban.
0

#30 User is offline   fouss 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 385
  • Joined: 05-October 10
  • Location:Bamako Mali

Posted 20 December 2010 - 03:52 AM

View PostJuban, on 18 December 2010 - 02:49 AM, said:

Hi all,

I've been very busy lately and I wish you forgive me to give no answer to your previous messages.
Seems like the demos applications are buggy, specially the Yii 1.1 one.
I will try to fix that as soon as possible and publish a corrected version.

Thanks for you patience and support.

Regards.

Alban.


Merci Juban de penser à nous!

Thank you for thinking of us
Posted Image
0

#31 User is offline   dans 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 20
  • Joined: 21-October 10

Posted 29 January 2011 - 11:29 PM

I have a table "service" which has multiple "transactions" associated to it - I have this part working well. It gets complicated because each transaction has a cost associated with it, and I want the cost of all the transactions to be shown in a separate field when I look at the "service" record.

I can sort of get this to work, but it only happens when I press save twice - so what I think is happening is that the transaction records are being created after the service record has been created/saved (thus not loading my custom behavior to calculate the total cost of all transactions).

Is there a better way I should be trying to achieve my outcome?
0

#32 User is offline   Juban 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 12-January 09
  • Location:Grenoble France

Posted 30 January 2011 - 04:47 AM

View Postdans, on 29 January 2011 - 11:29 PM, said:

I have a table "service" which has multiple "transactions" associated to it - I have this part working well. It gets complicated because each transaction has a cost associated with it, and I want the cost of all the transactions to be shown in a separate field when I look at the "service" record.

I can sort of get this to work, but it only happens when I press save twice - so what I think is happening is that the transaction records are being created after the service record has been created/saved (thus not loading my custom behavior to calculate the total cost of all transactions).

Is there a better way I should be trying to achieve my outcome?


Hi,

Could you give me the relations array you declared in you model please?
I'm nit sure I get your explanations right.

Thanks.
0

#33 User is offline   dans 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 20
  • Joined: 21-October 10

Posted 30 January 2011 - 07:57 AM

Sure thing! In my model Service.php...

public function behaviors()
{
return array(
'CSaveRelationsBehavior' => array(
'class' => 'application.components.CSaveRelationsBehavior',
'deleteRelatedRecords'=>false,
'relations' => array(
'stockTrans'=>array("message"=>"Please, check the Stock Items"),
),
),
'ServiceBehavior' =>'application.modules.service.components.ServiceBehavior',
);
}

public function relations()
{
return array(
'stockTrans' => array(self::HAS_MANY, 'StockTrans', 'sr_id'),
);
}

and in my Service view controller...

public function actionView($id)
{
$model=$this->loadModel($id);
if(isset($_POST['Service']))
{
$model->attributes=$_POST['Service'];
$model->setRelationRecords('stockTrans',is_array(@$_POST['StockTrans']) ? $_POST['StockTrans'] : array());
if(isset($_POST['addStockTrans'])) { $model->addStockTrans(); }
if(isset($_POST['deleteStockTrans'])) $model->deleteStockTrans($_POST['idx']);
if($model->save()) {
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('view',array('model'=>$model));
}


So the Service model calls a behavior that does some calculations to determine the total cost of all the "total" columns in the StockTrans model (via an afterSave). This behavior is not being called after the execution of the StockTrans. Well it kind of is, but it requires two saves to actually "see" the value of the total of the related "StockTrans" records as from what I can gather it is being executed after the save of the first Service record?
0

#34 User is offline   Juban 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 12-January 09
  • Location:Grenoble France

Posted 30 January 2011 - 11:54 AM

View Postdans, on 30 January 2011 - 07:57 AM, said:

So the Service model calls a behavior that does some calculations to determine the total cost of all the "total" columns in the StockTrans model (via an afterSave). This behavior is not being called after the execution of the StockTrans. Well it kind of is, but it requires two saves to actually "see" the value of the total of the related "StockTrans" records as from what I can gather it is being executed after the save of the first Service record?


I'm starting to get it :)
It would be helpfull if you could provide the ServiceBehavior code to see what could go wrong.
I'm not too sure about the order in which the different behaviors get called. Perhaps, it's a related issue.

Thanks.

Alban.
0

#35 User is offline   dans 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 20
  • Joined: 21-October 10

Posted 30 January 2011 - 06:36 PM

ServiceBehavior file attached :)

Attached File(s)


0

#36 User is offline   Juban 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 12-January 09
  • Location:Grenoble France

Posted 31 January 2011 - 02:23 AM

Hi,

After a quick look to your code, I think you should inactivate the transactional mode of the SaveRelationsBehavior ($transactional property must be set to false). Can you try that and let me know?

Thanks.

Alban.
0

#37 User is offline   gr8abbasi 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 28-April 11

Posted 06 May 2011 - 07:01 AM

Hi,

I am using CSaveRelationsBehavior (Latest version available) extension but getting this error
"An error occured during the save of contactPhones"
for the corresponding relation.
Please any help will be highly appreciation.

My Controller
public function actionCreate()
{
$model=new Contacts;

$model->addPhone();
$model->addWebsite();
$model->addEmail();


if(isset($_POST['Contacts']))
{
$model->attributes=$_POST['Contacts'];
// Set relations attributs values
$model->setRelationRecords('contactPhones',is_array(@$_POST['ContactPhones']) ? $_POST['ContactPhones'] : array());
$model->setRelationRecords('contactEmails',is_array(@$_POST['ContactEmails']) ? $_POST['ContactEmails'] : array());
$model->setRelationRecords('contactWebsites',is_array(@$_POST['ContactWebsites']) ? $_POST['ContactWebsites'] : array());

if($model->save()){
$this->redirect(array('view','id'=>$model->id));
}else{
print_r($model->getErrors());exit;
}
}



$this->render('create',array(
'model'=>$model,
));

My Model

public function addPhone() {
$this->addRelatedRecord('contactPhones',new ContactPhones,true);
}



public function addWebsite() {
$this->addRelatedRecord('contactWebsites',new ContactWebsites,true);
}



public function addEmail() {
$this->addRelatedRecord('contactEmails',new ContactEmails,true);
}

Thanks in advance
0

#38 User is offline   Juban 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 12-January 09
  • Location:Grenoble France

Posted 07 May 2011 - 02:37 AM

View Postgr8abbasi, on 06 May 2011 - 07:01 AM, said:

Hi,

I am using CSaveRelationsBehavior (Latest version available) extension but getting this error
"An error occured during the save of contactPhones"
for the corresponding relation.
Please any help will be highly appreciation.

My Controller
public function actionCreate()
{
$model=new Contacts;

$model->addPhone();
$model->addWebsite();
$model->addEmail();


if(isset($_POST['Contacts']))
{
$model->attributes=$_POST['Contacts'];
// Set relations attributs values
$model->setRelationRecords('contactPhones',is_array(@$_POST['ContactPhones']) ? $_POST['ContactPhones'] : array());
$model->setRelationRecords('contactEmails',is_array(@$_POST['ContactEmails']) ? $_POST['ContactEmails'] : array());
$model->setRelationRecords('contactWebsites',is_array(@$_POST['ContactWebsites']) ? $_POST['ContactWebsites'] : array());

if($model->save()){
$this->redirect(array('view','id'=>$model->id));
}else{
print_r($model->getErrors());exit;
}
}



$this->render('create',array(
'model'=>$model,
));

My Model

public function addPhone() {
$this->addRelatedRecord('contactPhones',new ContactPhones,true);
}



public function addWebsite() {
$this->addRelatedRecord('contactWebsites',new ContactWebsites,true);
}



public function addEmail() {
$this->addRelatedRecord('contactEmails',new ContactEmails,true);
}

Thanks in advance


Hi,

First thing to ckeck is that there are no 'required' rules in your relation model applying to the foreign key to your Contact model.
If you generated the model with gii, it will be the case by default, so you should remove the rule by hand.

Please, let me know if this is working now.

Regards.

Alban.
0

#39 User is offline   dans 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 20
  • Joined: 21-October 10

Posted 17 May 2011 - 06:16 AM

Hi Alban,

I've just revisited this code (I put up with the "press twice" bug for a while now! :) I've re-written some of my code and this issue that I reported above still exists.

In summary:

* I use this CSaveRelationsBehavior to set the line items to a Request record.
* I would like to populate the SUM of the line items on the Request record.
* For this to occur it only sets the correct SUM on the 2nd save of the record.

I have worked out (I think?:) that this happens because Request record is being saved prior to the line items/related records, thus when the SUM is performed the old value is displayed.

I have tried using both true and false for transactional mode, but I see no difference.

I am attempting to perform the following calculation on the beforeSave() of the Request.

$query = Yii::app()->db->createCommand()->select('SUM(total) as SUM')->from(ServiceRequestStockTrans::model()->tableName())->where("sr_id=:sr_id", array('sr_id'=>$this->id))->queryRow();

So I know it's all about the timing and when the variables are set, and it makes sense why it occours... But I am not sure about the best approach to solve it? Do you have any suggestions? :)

Thanks!
0

#40 User is offline   Juban 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 12-January 09
  • Location:Grenoble France

Posted 21 May 2011 - 03:49 AM

View Postdans, on 17 May 2011 - 06:16 AM, said:

Hi Alban,

I've just revisited this code (I put up with the "press twice" bug for a while now! :) I've re-written some of my code and this issue that I reported above still exists.

In summary:

* I use this CSaveRelationsBehavior to set the line items to a Request record.
* I would like to populate the SUM of the line items on the Request record.
* For this to occur it only sets the correct SUM on the 2nd save of the record.

I have worked out (I think?:) that this happens because Request record is being saved prior to the line items/related records, thus when the SUM is performed the old value is displayed.

I have tried using both true and false for transactional mode, but I see no difference.

I am attempting to perform the following calculation on the beforeSave() of the Request.

$query = Yii::app()->db->createCommand()->select('SUM(total) as SUM')->from(ServiceRequestStockTrans::model()->tableName())->where("sr_id=:sr_id", array('sr_id'=>$this->id))->queryRow();

So I know it's all about the timing and when the variables are set, and it makes sense why it occours... But I am not sure about the best approach to solve it? Do you have any suggestions? :)

Thanks!


Hi,

Obviously, the SUM calculation should be performed at the very end of the process. So, it makes sense that it doesn't work in the beforeSave Event.
Looking at your ServiceBehavior, I was wondering if you tried to make it a subclass of the CSaveRelationsBehavior instead of CActiveRecordBehavior?
Another thing to try is to call the refresh() method of your main ActiveRecord before making the sum computation to be sure you have it uptodate.

Regards.

Alban.
0

Share this topic:


  • (3 Pages)
  • +
  • 1
  • 2
  • 3
  • You cannot start a new topic
  • You cannot reply to this topic

2 User(s) are reading this topic
0 members, 2 guests, 0 anonymous users