【问题标题】:Saving related data in MVC (cakephp)在 MVC 中保存相关数据(cakephp)
【发布时间】:2011-04-27 15:14:28
【问题描述】:

我一遍又一遍地阅读来自cakephpbook 却不明白如何保存相关数据。我有一个名为 Works 的部分和一个名为 Furnitures 的部分,其中可以包含 Images

    作品
  • 身份证
  • 标题
  • 身体
  • 网址
  • user_id
  • 已创建
  • 修改
  • 有效
    家具
  • 身份证
  • 标题
  • 身体
  • 网址
  • user_id
  • 已创建
  • 修改
  • 有效
    图片
  • 身份证
  • 姓名
  • 类型
  • 文件路径
  • user_id
  • 已创建
  • 修改
  • 有效

我已经为每个实体(WorkFurnitureImage)创建了一个 MVC,现在我正在尝试使用 add 视图将Work 添加到我的站点:

<script>/* script for .add_image, Work and other models can have 0 or more images */</script>
<div><?php echo $this->Form->input('Work.title', array('value'=>'titolo', 'label' => 'Nome lavoro')); ?></div>
<div><?php echo $this->Form->input('Work.body', array('type' => 'textarea', 'value'=>'description', 'label' => 'Descrizione')); ?></div>
<div><?php echo $this->Form->input('Work.url', array('value'=>'http://', 'label'=> false)); ?></div>
<div>Immagini</div>
<div><?php echo $this->Form->input('Image.name', array('label'=> false, 'value'=>'Nome immagine'));?></div>
<div><?php echo $this->Form->file('Image.file'); ?></div>
<div><div class="add_image">Add image</div></div>
<div><?php echo $this->Form->end('Inserisci lavoro'); ?></div>

这仅保存Work 数据,没有Image 相关数据,我想我在ModelController 中遗漏了一些东西:

<?php

class Work extends AppModel {
    var $name = 'Work';
    var $belongsTo = array ('User');
    var $hasAndBelongsToMany = array (
        'Image' => array (
            'className' => 'Image',
            'order' => 'Image.created DESC',
            'exclusive' => true,
            'dependent' => true // this will remove all images related to article
        ),
        'Tag' => array (
            'className' => 'Tag',
            'order' => 'Tag.name DESC'
        )
    );

    var $validate = array (
        'title' => array(
            'rule' => array('maxLength', 60),
            'allowEmpty' => false
        ),
        'body' => array (
            'rule' => array('maxLength', 250),
            'allowEmpty' => false
        ),
        'url' => array (
            'rule' => array('url', true),
            'allowEmpty' => true
        )
    );

    function parentNode () {
        return null;
    }
}

?>

WorksController:

<?php

class WorksController extends AppController {

    var $name = 'Works';
    var $components = array ('Session');

    function index () {
        $this->set('works', $this->Work->find('all'));
    }

    function view () {
        $this->Work->id = $id;
        $this->set('work', $this->Work->read());
    }

    function add () {
        if (!empty($this->data)) {
            $work = $this->Work->save($this->data);
            if (!empty($work)) {
                // this is wrong, but what should I write?
                // $this->data['Image']['user_id'] = $this->Work->User->id;
                // $this->Work->Image->saveAll($this->data);
                $this->Session->setFlash ('Lavoro inserito correttamente');
                $this->redirect(array('action'=>'index'));
            }
        }
    }
}
?>

图像模型:

<?php

class Image extends AppModel {
    var $name = 'Image';

    var $hasAndBelongsToMany = array (
        'Work' => array (
            'className' => 'Work'
        ),
        'Furniture' => array (
            'className' => 'Furniture'
        )
    );

    var $actsAs = array ('FileUpload.FileUpload' => array (
        'uploadDir' => 'img/shared',// 'forceWebroot' => true, is default
        'allowedTypes' => array(
            'jpg' => array('image/jpeg', 'image/pjpeg'),
            'jpeg' => array('image/jpeg', 'image/pjpeg'), 
            'gif' => array('image/gif'),
            'png' => array('image/png','image/x-png'),
        ),
        'maxFileSize' => 614400, // 600kB in bytes
        'unique' => true
    ));

    // in the wiew file: echo $form->input('Image.file', array('type' => 'file'));

    var $validate = array (
        'name' => array (
            'rule' => 'notEmpty',
            'message' => 'Nome dell\'immagine in fase di cariamento mancante'
        ),
        'filename' => array (
            'rule' => 'notEmpty',
            'message' => 'Nome dell\'immagine in fase di cariamento mancante'
        )
    );
}
?>

这只会保存Works 数据的一部分:

    作品
  • id - 好的
  • 标题 - 好的
  • 身体 - 好的
  • 网址-好的
  • user_id - 为 0
  • 已创建 - 好的
  • 修改-好的
  • 活动-为0

我应该如何在Works 中实现Images

我想添加一个名为images_works 的数据库表来链接WorksImagesfurnitures_images 以链接FurnituresImages,我应该怎么做才能继续修复user_id missing error

【问题讨论】:

  • 你没有在数据库中丢失你的外键吗?如果没有相关的外键,Cake 就无法查看事物如何组合在一起,即使您在模型中定义它们也是如此。

标签: model-view-controller cakephp save


【解决方案1】:

第一

<?php
class WorkdsController extends AppController
    var $components = array('Session', 'Auth');
    if($this->Wok->create($data) && $this->Work->save($this->data)){
        $work_id = $this->Work->getID;
        // and than use work_id work with work id. then you should somehow get user_id
        // for example $this->Auth->user(id');
    }
}

那么,如果您想以上述方式(hasMany)将图像链接到作品,那么您应该在图像表中添加一个 work_id。

否则创建一个新表 images_works (id, image_id, work_id) 并使用 $hasAndBelongsToMany,而不是 $hasMay

【讨论】:

  • 首先感谢您的宝贵帮助,它返回一个错误Notice (8): Undefined variable: data [APP/controllers/works_controller.php, line 21] 我认为是在if($this-&gt;Work-&gt;create($data) &amp;&amp; $this-&gt;Work-&gt;save($this-&gt;data)),您能解决它吗?
  • 确定已修复 $this-&gt;Work-&gt;create($this-&gt;data)$this-&gt;Work-&gt;getID();
  • 现在user_id 工作正常,但images_works 的所有user_idwork_idimage_id0images 表仍然是空的
【解决方案2】:

输入的名称必须不同,并且根据 CakePHP 期望 Image 到 saveAll() 的数据结构。将名称设为 [Image][counter][name] 或 [Counter][Image][name]。 (不确定蛋糕模型期望的是哪一张)否则您将收到唯一一张图片,并且只会保存一张图片。

还要确保表单元素具有为文件上传设置的属性enctype

【讨论】:

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