CakePHP中的数据保存为空白

时间:2011-09-28 21:48:30

标签: cakephp cakephp-appmodel

我有一个foreach循环,使用cakePHP

将一堆记录保存到表中
foreach($interests as $id){
                $this->data['UserInterest']['user_id'] = $user_id;
                $this->data['UserInterest']['interest_id'] = $id;
                $this->data['UserInterest']['other_interest'] = $other;
                $UserInterest = new UserInterest;
                if(!$UserInterest->save($this->data)) {
                    $this->Session->setFlash(__l('Failed to save Interests.') , 'default', null, 'error');
                }
            }

除了其他兴趣外,所有保存都很好

更新:

我做了以下

如果我这样做,我可以完美地将它排除在外

$this->data['UserInterest']['other_interest'] = $other;
echo $this->data['UserInterest']['other_interest'];
                    $UserInterest = new UserInterest;

但不知何故,它保存为空白?

我的数据库布局如下所示

CREATE TABLE IF NOT EXISTS `users_interests` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) NOT NULL,
  `interest_id` bigint(20) NOT NULL,
  `other_interest` varchar(150) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
)

和我的模特一样

<?php
class UserInterest extends AppModel
{
    var $name = 'UserInterest';

    var $useTable="users_interests";

    //$validate set in __construct for multi-language support
    //The Associations below have been created with all possible keys, those that are not needed can be removed
    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
        ) ,
        'Interests' => array(
            'className' => 'Interest',
            'foreignKey' => 'interest_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
        )
    );
    function __construct($id = false, $table = null, $ds = null) 
    {
        parent::__construct($id, $table, $ds);
        $this->validate = array(
            'user_id' => array(
                'rule' => 'numeric',
                'allowEmpty' => false,
                'message' => __l('Required')
            )
        );
    }
}
?>

我做错了吗?

更新:

我做了以下

$this->data['UserInterest']['user_id'] = $user_id;
                $this->data['UserInterest']['interest_id'] = $id;
                $this->data['UserInterest']['other_interest'] = $other;
                 echo '<pre>';
                var_dump($this->data['UserInterest']);
                var_dump($other);
                var_dump($this->data['UserInterest']['other_interest']);

                $this->UserInterest = ClassRegistry::init('UserInterest');

并且var_dump会产生以下内容,但仍然没有保存

array(3) {
  ["user_id"]=>
  string(3) "659"
  ["interest_id"]=>
  string(2) "10"
  ["other_interest"]=>
  string(17) "Share Investments"
}
string(17) "Share Investments"
string(17) "Share Investments"

1 个答案:

答案 0 :(得分:1)

老帖子,但想在这里添加....

始终拥有

$this->Modelname->create();

在循环中用循环保存多个记录。最常见的情况是导致错误。