CActiveRecord cannot insert Null (MSSQL)

Hi all, I’m using the User-Model found at http://yii-user.googlecode.com/

I used this before with MySQL and everything was fine now I’m doing a different project with SQL. The extension did not come with a MsSql data query so I changed the MySQL a little to make it work. I can login but I have problems making a user. I get this error

Which is refering to this




               $profile->user_id=0;

             if($model->validate()&&$profile->validate()) {

                 $model->password=Yii::app()->controller->module->encrypting($model->password);

                 if($model->save()) {

                     $profile->user_id=$model->id;

                    $profile->save();

                }

                $this->redirect(array('view','id'=>$model->id));

            } else $profile->validate();

        }




My only thought is that " $profile->user_id=$model->id;" is not being executed early enough. So I tried using beforeSave like this inside my AdminController





public function beforeSave()

        {

		  if(parent::beforeSave())

                {

		

		$profile->user_id=$model->id;

		}

		}



Still no luck. I also tried removing "$profile->user_id=0;".

Not sure if I’m using the beforSave correctly,

Does anyone know how I can get this working

Thanks

Your function beforeSave() should return true to proceed saving of model.

Method beforeSave() must be declared in your model, not in Controller.

Thanks for the reply Layne

So I tried


public function beforeSave()

	 

	 

        {

		

		$User=new User;

		  if(parent::beforeSave())

                {

		

		$this->user_id= $User->id;

		}

		

		return true;

		}

User being where the id is to be taken from. I still get the same error. I put this code on the Profile Model.

Hey guys I’m still struggling with this, The User table where the ID is to be taken from saves correctly. I can view on my DB, however the profile table takes the ID of User and uses that as its PK. What I don’t understand is that if User is being saved why can’t I grab it’s PK and put it into the Profiles’s table like this $profile->user_id=$model->id; or the way I done with beforeSave?

Thanks

again

By


$User=new User;

you create a NEW object, which has an empty id, you should pass $model object to your beforeSave() method if you want to use it there. I think it would be better for you to use the approach you used before, when you’ve got the initial error.




if($model->save()) {

             		$profile->user_id=$model->id;

                    $profile->save();

                }

I didn’t work with [color="#1C2837"][size=“3”]MsSql, but the error you get seems isn’t an expected behavior for any db.[/size][/color]

[color="#1C2837"][size="3"]What is your full error info?[/size][/color]

[color="#1C2837"][size="3"] Did you check $model->save() performed correctly and you have this row inserted into the table?[/size][/color]

[color="#1C2837"][size="3"]Could you var_dump $model->id after the $model->save()?[/size][/color]

[color="#1C2837"][size="3"]Also, if you validate models manually before saving,[/size][/color]

[color="#1c2837"][size="2"]


if($model->validate()&&$profile->validate()) {

[/size]

[/color]then you most probably will like to switch off the same validation on saving, passing false as an argument to save(),e.g.


$model->save(false)

http://www.yiiframew…ord#save-detail

I don’t understand how to do so, Can you show me please? Basically I’m doing beforeSave() inside my Profile model which needs a variable (id) from my User model


CDbException


CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot insert the value NULL into column 'user_id', table 'panasonic.dbo.profiles'; column does not allow nulls. INSERT fails.. The SQL statement executed was: INSERT INTO [dbo].[profiles] ([lastname], [firstname], [birthday], [user_id]) VALUES (:yp0, :yp1, :yp2, :yp3)


C:\xampp\framework\db\CDbCommand.php(354)


342             return $n;

343         }

344         catch(Exception $e)

345         {

346             if($this->_connection->enableProfiling)

347                 Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');

348             $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;

349             $message = $e->getMessage();

350             Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',

351                 array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');

352             if(YII_DEBUG)

353                 $message .= '. The SQL statement executed was: '.$this->getText().$par;

354             throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',

355                 array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);

356         }

357     }

358 

359     /**

360      * Executes the SQL statement and returns query result.

361      * This method is for executing an SQL query that returns result set.

362      * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative

363      * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing

364      * them in this way can improve the performance. Note that if you pass parameters in this way,

365      * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.

366      * binding methods and  the input parameters this way can improve the performance.

Stack Trace

#0	

–  C:\xampp\framework\db\ar\CActiveRecord.php(1014): CDbCommand->execute()

1009         {

1010             Yii::trace(get_class($this).'.insert()','system.db.ar.CActiveRecord');

1011             $builder=$this->getCommandBuilder();

1012             $table=$this->getMetaData()->tableSchema;

1013             $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));

1014             if($command->execute())

1015             {

1016                 $primaryKey=$table->primaryKey;

1017                 if($table->sequenceName!==null)

1018                 {

1019                     if(is_string($primaryKey) && $this->$primaryKey===null)

#1	

–  C:\xampp\framework\db\ar\CActiveRecord.php(787): CActiveRecord->insert(null)

782      * @return boolean whether the saving succeeds

783      */

784     public function save($runValidation=true,$attributes=null)

785     {

786         if(!$runValidation || $this->validate($attributes))

787             return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);

788         else

789             return false;

790     }

791 

792     /**

#2	

–  C:\xampp\htdocs\panasonic\protected\modules\user\controllers\AdminController.php(89): CActiveRecord->save()

84                 $model->password=Yii::app()->controller->module->encrypting($model->password);

85                 if($model->save()) {

86                 $profile->user_id=$model->id;

87                 

88                 var_dump($model->id);

89                     $profile->save();

90                     }

91                     

92                 

93                 

94                 $this->redirect(array('view','id'=>$model->id));

#3	

–  C:\xampp\framework\web\actions\CInlineAction.php(50): AdminController->actionCreate()

45         $controller=$this->getController();

46         $method=new ReflectionMethod($controller, $methodName);

47         if($method->getNumberOfParameters()>0)

48             return $this->runWithParamsInternal($controller, $method, $params);

49         else

50             return $controller->$methodName();

51     }

52 

53 }

#4	

+  C:\xampp\framework\web\CController.php(309): CInlineAction->runWithParams(array("r" => "user/admin/create"))

#5	

+  C:\xampp\framework\web\filters\CFilterChain.php(134): CController->runAction(CInlineAction)

#6	

+  C:\xampp\framework\web\filters\CFilter.php(41): CFilterChain->run()

#7	

+  C:\xampp\framework\web\CController.php(1146): CFilter->filter(CFilterChain)

#8	

+  C:\xampp\framework\web\filters\CInlineFilter.php(59): CController->filterAccessControl(CFilterChain)

#9	

+  C:\xampp\framework\web\filters\CFilterChain.php(131): CInlineFilter->filter(CFilterChain)

#10	

+  C:\xampp\framework\web\CController.php(292): CFilterChain->run()

#11	

+  C:\xampp\framework\web\CController.php(266): CController->runActionWithFilters(CInlineAction, array("accessControl"))

#12	

+  C:\xampp\framework\web\CWebApplication.php(276): CController->run("create")

#13	

+  C:\xampp\framework\web\CWebApplication.php(135): CWebApplication->runController("user/admin/create")

#14	

+  C:\xampp\framework\base\CApplication.php(162): CWebApplication->processRequest()

#15	

–  C:\xampp\htdocs\panasonic\index.php(13): CApplication->run()

08 defined('YII_DEBUG') or define('YII_DEBUG',true);

09 // specify how many levels of call stack should be shown in each log message

10 defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);

11 

12 require_once($yii);

13 Yii::createWebApplication($config)->run();

14 

Not sure if you want to see the rest.

$model->save performs correctly, my info is there and on my view. If I want to view a specific user it displays with an error because Profile is not being saved.

I tried var_dump but it doesn’t work. The interesting thing is if I omit profile->save the info is saved on $model->save but I get a 404 error for my redirection. Even though if I got to the page manually it displays with this error


Fatal error: Call to a member function getAttribute() on a non-object in C:\xampp\htdocs\panasonic\protected\modules\user\views\admin\view.php on line 30

Referring to a code that calls $profile.

Thanks for your reply

Let’s forget beforeSave() for now, as it’s not the clue question at the moment and I don’t think you really need it here.

As I see the main problem is you have saved $model, then you want to set $profile->user_id to just saved $model->id, but this $model->id is empty (null). That’s why I wanted first to have a clear understanding $model->id is NULL after $model->save(), it could be done by





if($model->save()) {

                 var_dump($model->id);

exit;

                 $profile->user_id=$model->id;

                     $profile->save();

                     }



Maybe this is the issue at all?

Thanks

This is what I get


string(0) ""

So… basically nothing is on $model->id but when I check my DB for User everything is there including $model->id

I tried that link and it worked. Thank you so much.

You’re a star

Oh, nice to hear the problem is solved :)