0

我想我错过了一些东西,因为这太明显了,我无法想象它真的是这样工作的:

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);
    }
}

为什么它存储对相关对象的引用,但没有相应地更新外键属性?构建插入查询的 sql 命令构建器也不识别相关对象/外键事物 >

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。

我的问题:我在这里错过了什么......

4

1 回答 1

0

没有遗漏任何东西。这就是它的工作方式。您必须直接设置属性,而不是通过关系隐式设置。

于 2013-07-22T20:50:50.050 回答