2011-02-01 87 views
0

我试图创建愿望清单。CakePHP无法保存数据(HABTM)

有用户和产品型号。用户有一个愿望清单。愿望清单有许多产品。

我使其用户的心愿和心愿具有产品是这样我就可以有一个像wish_lists一个url原因/添加/:PRODUCT_ID


我创建的表称为wish_listsiduser_id,并name

我还创建了一个名为products_wish_lists的表,其中wish_list_idproduct_id

我在这里做的是心愿控制器:

class WishListsController extends AppController 
{ 
    var $hasOne = 'User'; 
    var $hasMany = 'Product'; 

    function beforeFilter() 
    {   
     parent::beforeFilter();  
     $this->Auth->deny('add');  
    } 

    function add($id) 
    { 
     $user = $this->Session->read("Auth.User"); 

     $this->WishList->set(array(
      'User.id' => $user['id'], 
      'Product.id'=>$id, 
      'WishList.name'=>'default' 
     )); 

     if($this->WishList->save()) 
     { 
      $this->Session->setFlash('This product has been added to your wishlist.', 'flash_good'); 
     } 
     else 
     { 
      $this->Session->setFlash('Error: This product was not added to your wishlist.', 'flash_bad'); 
     } 

     $this->redirect(array("controller"=>"products","action"=>"view",$id)); 
    } 
} 

当我去localhost/wish_lists/add/1它告诉我,每次它保存。但没有数据被添加到数据库。

不知道我在做什么错?

回答

0

我从来不这样做,我总是建立一个$data数组作为参数传递给保存功能。

因此,我不确定该语法是否允许您指定模型,例如'Model.field'。无论如何,$this->WishList->save()只会保存Wishlist部分。

更好,在我看来,应该是:

$saveData = array(
    'User'=>array('id'=>$user['id']), 
    'Product'=>array('id'=>$id), 
    'WishList'=>array('name'=>'default')); 
$this->WishList->saveAll($saveData); 

(或类似的东西,我一直在为过去三个月编程ColdFusion和我的PHP可以有点怪僻)

0

你正在设置数组错误。它应该是$ data ['User'] ['id'] = 123; $ data ['Product'] ['id'] = 321;

$ this-> Wishlist-> saveAll($ data);

保存名称没有意义,因为可以从产品表中找到该名称。

,你可以看看这里的代码更多的想法https://github.com/Infinitas-Plugins/shop

有下面的链接,节省产品加入购物车或心愿(不同分贝的)作为它的几乎是同样的事情,一个通用组件的方法。

https://github.com/Infinitas-Plugins/shop/blob/master/controllers/components/shop.php#L62