【问题标题】:Relation not being saved with CakePHP hasMany relationship未使用 CakePHP 保存关系 hasMany 关系
【发布时间】:2012-10-23 13:54:37
【问题描述】:

我有两个模型:EventVenue。一个 Event 属于一个 Venue,一个 Venue 可以有多个 Event。我正在尝试使用一个表单同时保存一个事件和场地。到目前为止,这是我在控制器中所拥有的:

public function add() {
    if ($this->request->is('post')) {
        if ($this->Event->saveAll($this->request->data)) {
            $this->Session->setFlash('Event successfully saved');
        }
    }
}

这是我的表格:

<?php
    echo $this->Form->create('Event');
    echo $this->Form->inputs(array(
        'legend' => 'Event Details',
        'Event.date',
        'Event.title'
    ));
    echo $this->Form->inputs(array(
        'legend' => 'Venue Details',
        'Venue.name',
        'Venue.street_address',
        'Venue.locality' => array('label' => 'Town/city'),
        'Venue.postal_code'
    ));
    echo $this->Form->end('Save Event');
?>

很简单。

现在,EventVenue 记录都已创建。但是我的events 表中的venue_id 为零;它没有设置为新创建的 Venue 的 ID。我该如何纠正这个问题?我相信这很简单!

编辑:我的Event 模特:

<?php
class Event extends AppModel {

    public $name = 'Event';
    public $actsAs = array(
        'Containable'
    );
    public $belongsTo = array(
        'Venue'
    );
}

我的Venue 模特:

<?php
class Venue extends AppModel {
    public $name = 'Venue';
    public $hasMany = array(
        'Event'
    );
}

【问题讨论】:

  • 您的关联设置是否正确?我觉得还可以
  • 我相信是的。我在问题中添加了我的模型定义。
  • Cake 建议您需要先保存主/父模型,猜测在这种情况下为VenueVenue (parent) hasMany Event (children)。所以尝试做同样的事情,但改用 Venue 控制器/模型/视图。
  • 你能把$this->request->data的内容贴出来吗?

标签: cakephp model


【解决方案1】:

看来我在使用saveAll() 方法时需要使用array('deep' =&gt; true)

if ($this->Event->saveAll($this->request->data, array('deep' => true))) {
    $this->Session->setFlash('Event successfully saved');
}

感谢所有仍然发表评论的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多