Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually packaging data for CakePHP's save()

Tags:

php

save

cakephp

I'm trying to package up some data for the save() function in cakephp. I'm new to PHP, so I'm confused about how to actually write the below in code:

Array
(
    [ModelName] => Array
        (
            [fieldname1] => 'value'
            [fieldname2] => 'value'
        )
)

Thank you!

like image 844
kurisukun Avatar asked Mar 18 '26 19:03

kurisukun


1 Answers

To answer your question, you can create the array structure you need, and save it, by doing this:

<?php
$data = array(
    'ModelName' => array(
        'fieldname1' => 'value',
        'fieldname2' => 'value'
    )
);
$this->ModelName->save($data);
?>

Please note: Based on what you've written above in your comments it looks like you're not keeping to the CakePHP conventions. It's possible to do things this way but you'll save yourself a lot of time and trouble if you decided to stick with the CakePHP defaults as much as possible, and only do it your own way when you have a good reason to.

A couple things to remember are:

  1. Model names should be singular. This means that your model should be called Follower instead of Followers.
  2. The model's primary key in the database should be named just id, not followers_id, and should be set as PRIMARY KEY and AUTO_INCREMENT in your database.

If you decide not to follow the conventions you'll probably find yourself scratching your head, wondering why things aren't working, every step of the way. Try having a look at the CakePHP documentation for more details.

like image 127
Mark Northrop Avatar answered Mar 21 '26 09:03

Mark Northrop