【问题标题】:cakephp saveAll associated model field is not being savedcakephp saveAll 关联的模型字段未保存
【发布时间】:2016-12-09 22:38:11
【问题描述】:

我目前使用的是 cakephp 2.2.3。

我有以下模型关联:

VehicleModel -> 车辆 -> 订单

计划 -> 订单

车辆HABTM标签

在 Vehicle 控制器中,添加动作,我有:

if(!empty($this->request->data)) {

    if($this->Vehicle->saveAll($this->request->data)) {

        $this->Session->setFlash('Vehicle was successfully added.');
    }

}

$this->request->data 数组的格式如下:

array(
    'VehicleModel' => array(
        'category_id' => '2',
        'make_id' => '1'
    ),
    'Order' => array(
        'plan_id' => '2'
    ),
    'Vehicle' => array(
        'vehicle_model_id' => '13',
        'price' => ' 8700',
        'year' => '1994',
        'km' => '100',
        'color' => '61',
        'fuel' => '1',
        'gear' => '20',
        'type' => '51',
        'city' => 'Rio de Janeiro',
        'state' => 'RJ'
    ),
    'Tag' => array(
        'Tag' => array(
            (int) 0 => '69',
            (int) 1 => '11'
        )
    )
)

订单表具有以下字段:

id , plan_id , vehicle_id , created , modified。

车型:

class Vehicle extends AppModel {

    public $belongsTo = array('User' , 'VehicleModel');
    public $hasMany = array('Order' , 'Image');
    public $hasAndBelongsToMany = array('Accessory' , 'Tag');
}

订购型号:

class Order extends AppModel {

    public $belongsTo = array('Vehicle' , 'Part' , 'Plan');

    public $validate = array(
        'plan_id' => array(
            'rule' => 'notEmpty'
        )
    );

}

我遇到的问题是 Order.plan_id 字段没有被保存,尽管所有其他字段都正常保存。我做错了什么?

【问题讨论】:

  • 明确一点,当我手动进行多次保存时,一切正常。我的意思是,当我写:$this->Vehicle->save(),然后设置$this->request->data['Order']['vehicle_id'] = $this->Vehicle->id,最后设置$this->Vehicle->Order->save(),一切正常。是 saveAll 给我带来了麻烦。
  • 你能发布模型车辆/订单吗?
  • 在旧版本的 cake 中,如果主模型数据不是数据数组中的第一个,则会出现不一致的行为 - 您使用的是什么版本的 cake?
  • 我已添加车辆/订单模型。至于我用的版本是2.2.3。

标签: cakephp model


【解决方案1】:

要明确一点,当我手动进行多次保存时,一切 工作得很好。我的意思是,当我写的时候:

$this->Vehicle->save()

然后设置

$this->request->data['Order']['vehicle_id'] = $this->Vehicle->id

最后

$this->Vehicle->Order->save()

一切正常。是 saveAll 导致我 麻烦。

如果是这种情况,请查看$this->request->data['Order']['vehicle_id'] = $this->Vehicle->id 的位置。将此与您上面的 var 转储进行比较,订单从不包含与主模型的关系,这导致我问这是您要保存的新记录还是更新?如果您要设置新记录,我认为您可能不必在此处使用 saveAll,因为尚未设置主 ID。请看:

http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto

特别是:“如果系统中不存在任何关联的模型记录(例如,您想同时保存一个新用户及其相关的个人资料记录),您将需要先保存主模型或父模型。”

他们基本上做你正在做的长版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 2014-12-28
    • 1970-01-01
    • 2011-08-01
    • 2013-09-24
    • 1970-01-01
    相关资源
    最近更新 更多