Php Yii保存属于父对象的子对象时发生异常
我想我遗漏了一些东西,因为这太明显了,我无法想象它真的是这样工作的:Php Yii保存属于父对象的子对象时发生异常,php,activerecord,yii,belongs-to,Php,Activerecord,Yii,Belongs To,我想我遗漏了一些东西,因为这太明显了,我无法想象它真的是这样工作的: class ApiUser extends CActiveRecord {HAS_MANY ApiLog} class ApiLog extends CActiveRecord {BELONGS_TO ApiUser} 现在我想保存一个新的ApiLog记录: class ApiLog: /** * Logs a call to the API * * @param type $apiUser * @param
class ApiUser extends CActiveRecord {HAS_MANY ApiLog}
class ApiLog extends CActiveRecord {BELONGS_TO ApiUser}
现在我想保存一个新的ApiLog记录:
class ApiLog:
/**
* Logs a call to the API
*
* @param type $apiUser
* @param type $apiCall
* @param type $executionTime
* @param type $resultCount
* @param type $message
*/
public static function Log($apiUser, $apiCall, $executionTime = null, $resultCount = null, $message = '') {
$log = new ApiLog();
$log->apiUser = $apiUser;
$log->apiCall = $apiCall;
$log->clientIp = $_SERVER['REMOTE_ADDR'];
$log->executiontime = $executionTime;
$log->resultCount = $resultCount;
$log->logText = $message;
$log->save(false);
}
但这一行出现了一个例外:
$log->save(false)
CDbCommand无法执行SQL语句:SQLSTATE[23000]:
完整性约束冲突:1452无法添加或更新子行:
外键约束失败
预期行为:$log->apiUser=$apiUser
设置$log->apiuser\u id
属性。如果我手工操作($log->apiuser\u id=$apiuser->id
)没有问题,它会相应地保存对象
疯狂的是,我正在查看以下代码:
class CActiveRecord
/**
* PHP setter magic method.
* This method is overridden so that AR attributes can be accessed like properties.
* @param string $name property name
* @param mixed $value property value
*/
public function __set($name,$value)
{
if($this->setAttribute($name,$value)===false)
{
if(isset($this->getMetaData()->relations[$name]))
$this->_related[$name]=$value;
else
parent::__set($name,$value);
}
}
为什么它存储对相关对象的引用,但不相应地更新外键属性?构建insertquery的sql commandbuilder也不能识别相关的对象/外键thingy>
CActiveRecord
// ... //
public function insert($attributes=null) {
// ... //
$builder=$this->getCommandBuilder();
$table=$this->getMetaData()->tableSchema;
$command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
if($command->execute()) {
它只传递了属性数组,该数组不包含集合相关对象,只传递了记录属性(其中包含$apiuser\u id
),但没有从相关对象检索外部id
我的问题:我在这里遗漏了什么…没有遗漏任何东西。这就是它的工作方式。您必须直接设置属性,而不是通过关系隐式设置属性。但是,为什么uu set方法将对象存储到
$this->related
数组中?是否有一些Yii-ext行为为我修复了这个意想不到的行为?也许你可以说apiLog->apiUser->name
。