[英]Yii exception while saving child object that BELONGS_TO parent
我想我丢失了一些东西,因为这是如此明显,以至于我无法想象它真的可以这样工作:
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_id
属性。 如果我手动执行此操作( $log->apiuser_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也不识别相关对象/外键thing>
CActiveRecord
// ... //
public function insert($attributes=null) {
// ... //
$builder=$this->getCommandBuilder();
$table=$this->getMetaData()->tableSchema;
$command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
if($command->execute()) {
它只是传递了属性数组,该数组不包括设置的相关对象,而只是记录属性(确实包括$apiuser_id
),但没有从相关对象中检索外部ID。
我的问题:我在这里想念什么...
不丢失任何东西。 这就是它的工作方式。 您必须直接设置属性,而不是通过关系隐式设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.