开发者

CakePHP having trouble saving data (HABTM)

I am trying to create wish lists.

There are user and product models. A user has a wish list. A wish list has many products.

The reason I am making it user has wishlist and wishlist has products is so I can have a url like wish_lists/add/:product_id


I created a table called wish_lists with id, user_id, and name.

I also created a table called products_wish_lists with wish_list_id and product_id.

I made here is the wishlists controller:

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));
    }
}

When I go to localhost/wish_lists/add/1 It tells me everytime that it saved. but no data is being added to the database.

Not sure what I am do开发者_高级运维ing wrong?


I never do it that way, I always build a $data array to pass as parameter one to the save function.

I'm not sure, therefore, whether that syntax will allow you to specify the model as you have done, i.e. 'Model.field'. In any case, $this->WishList->save() will only save the Wishlist part.

Better, in my opinion, would be:

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

(or something like that, I've been programming ColdFusion for the last three months and my PHP can be a bit addled)


you are setting the array wrong. it should be $data['User']['id'] = 123; $data['Product']['id'] = 321;

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

There is no point saving the name as that can be found from the product table.

you can have a look at the code here for more ideas https://github.com/Infinitas-Plugins/shop

there is a generic component method in the following link that saves products to the cart or wishlist (different db's) as its pretty much the same thing.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜