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!
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:
Model names should be singular. This means that your model should be called Follower instead of Followers.
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.
I think you need to do like below:
$this->Followers->create();
$this->data['Followers']['user_id'] = $user_id;
$this->data['Followers']['follower_id'] = $follower_id; // If it is primary and auto increment than you don't need this line.
$this->Followers->save($this->data)
Related
I'm using in my project mandago ODM for mongodb.
http://mandango.org
I know that in MongoDb you can define JS functions on fields but I don't know how to do it with mandango. I create autoincrement ID field in more clever way than getting last record then incrementing it in PHP and saving in db. So my question is how to create an autoincrement field in mandago ODM?
I'd put some code but there's really nothing to put just pure code classes generated by Mondator.
After some research I have found out how to solve problem.
You need to add in your model mapping file 'idGenerator' => 'sequence'
in my case it looks as following:
$modelMapping = array(
'Model\User' => array(
'isEmbedded' => false,
'idGenerator' => 'sequence',
...
It will autoincrement _ID key in your document.
I am using a mongodb-codeigniter library by Alex Bilbie.
I have a collection called "user_visits". I insert into collection like below.
$query = $this->mongo_db->insert('user_restaurant_visits',[
'_id' => 1,
'user_id' => $user_id,
'pages_visited' => [
'page_id' => $restaurant_id
'visited' => [
'deal' => $purchase_deal,
'ordered' => $purchased_item
]
]
]);
Now all I would want to know is,
I would like to add the documents by "upsert=true" boolean flag as specified in here which will insert if the field is not present and update if the field is present. And I could not find a way to do so in the library I use! Am I misguided?
Is this a good way? is there anything wrong in the way I have organized the fields (I mean Schema as we say in RDBMS). I specifically ask this because, some feel nested arrays are better than embedded documents. like philnate says here in his answer and comments
If I'd want to upsert, increment a field, and addToSet, in the same query, is this possible with the library I currently use?
Let me know if I miss something, I can clarify in comments. I am totally new to NoSQL DBs.
I am sorry if that looked amaeturish.
Answer of one of your question :
How to Use "Upsert" in CodeIgniter while updating :
// Where Condition, if any
$this->mongo_db->where(array('condition_key' => 'condition_value'));
// Update Data Array
$this->mongo_db->set($mongoArray);
// Set Options
$option = array('upsert' => true);
// Call Update Function
$this->mongo_db->update('Collection_Name', $option);
I hope this will help you :)
I've got two tables - users and servers, and for the HABTM relationship, users_servers. Users HABTM servers and vice versa.
I'm trying to find a way for Cake to select the servers that a user is assigned to.
I'm trying things like $this->User->Server->find('all'); which just returns all the servers, regardless of whether they belong to the user.
$this->User->Server->find('all', array('conditions' => array('Server.user_id' => 1))) just gives an unknown column SQL error.
I'm sure I'm missing something obvious but just need someone to point me in the right direction.
Thanks!
Your table names are right. There are many ways to do this:
Use the Containable behavior
In your AppModel, set the following:
var $recursive = -1;
var $actsAs = array('Containable');
Then, use the following code to query your servers:
$userWithServers = $this->User->find('all', array(
'conditions' => array('User.id' => 1),
'contain' => array('Server')
));
Note that we are querying the User model, instead of the Server model to accomplish this.
Use bindModel
$this->Server->bindModel(array('hasOne' => array('UsersServer')));
$this->Server->find('all', array(
'fields' => array('Server.*'),
'conditions' => array('Server.user_id' => 1)
));
I personally don't recommend using bindModel a lot. Eventually, your code becomes a bit unmanagable. You should try using the Containable behavior whenever possible. The code looks cleaner and simpler. More on the bindModel method can be found here.
HTH.
I think you're supposed to name tour table user_servers.
I am creating multiple associations in one go and there are a few problems when it comes to saving.
I have the following code:
<?php
foreach($userData as $user) {
$data = array('User' => array('id' => $user['id']), 'Site' => array('id' => $user['site_id']));
$this->User->save($data);
}
?>
I have experimented with formatting the data array in different ways although I always encounter the same problems. Either the previous entries get moved when a new one is inserted or the current one gets updated.
I could just use the following although I need a behavior to trigger.
$this->User->SiteUser->save($data);
Edit: Also $this->User->create(); doesn't seem to do much.
The IRC helped work out what was wrong, once the unique key was set to false everything was able to save correctly.
//In the user model
var $hasAndBelongsToMany = array(
'Site' => array(
'className' => 'Site',
'unique' => false
)
);
Try resetting the id before a new save(), possibly on both models:
$this->User->id = null;
Cake decides whether to update or insert entries based on the set id, and save() sets an id automatically. Not sure why create() doesn't take care of this for you.
Also, if you want to save HABTM data, you should need to use saveAll() instead of save(). Also see this question.
OK, I am a little bit lost...
I am pretty new to PHP, and I am trying to use CakePHP for my web-site.
My DB is composed of two tables:
users with user_id, name columns
copies with copy_id, copy_name, user_id (as foreign key to users) columns.
and I have the matching CakePHP elements:
User and Copy as a model
UserController as controller
I don't use a view since I just send the json from the controller.
I have added hasMany relation between the user model and the copy model see below.
var $hasMany = array(
'Copy' => array(
'className' => 'Friendship',
'foreignKey' => 'user_id'
)
);
Without the association every find() query on the users table works well, but after adding the hasMany to the model, the same find() queries on the users stop working (print_r doesn't show anything), and every find() query I am applying on the Copy model
$copy = $this->User->Copy->find('all', array(
'condition' => array('Copy.user_id' => '2')
));
ignores the condition part and just return the whole data base.
How can I debug the code execution? When I add debug($var) nothing happens.
I'm not an expert, but you can start with the following tips:
Try to follow the CakePHP database naming conventions. You don't have to, but it's so much easier to let the automagic happen... Change the primary keys in your tabel to 'id', e.g. users.user_is --> users.id, copies.copy_id -->copies.id.
Define a view, just for the sake of debugging. Pass whatever info from model to view with $this->set('users', $users); and display that in a <pre></pre> block
If this is your first php and/or CakePHP attempt, make sure you do at least the blog tutorial
Make CakePHP generate (bake) a working set of model/view/controllers for users and copies and examine the resulting code
There's good documentation about find: the multifunctional workhorseof all model data-retrieval functions
I think the main problem is this:
'condition' => array('Copy.user_id' => '2')
It should be "conditions".
Also, stick to the naming conventions. Thankfully Cake lets you override pretty much all its assumed names, but it's easier to just do what they expect by default.
The primary keys should be all named id
The controller should be pluralised: UsersController
First off, try as much as possible to follow CakePHP convention.
var $hasMany = array(
'Copy' => array(
'className' => 'Friendship',
'foreignKey' => 'user_id'
)
);
Your association name is 'Copy' which is a different table and model then on your classname, you have 'Friendship'.
Why not
var $hasMany = array(
'Copy' => array('className'=>'Copy')
);
or
var $hasMany = array(
'Friendship' => array('className'=>'Friendship')
);
or
var $hasMany = array(
'Copy' => array('className'=>'Copy'),
'Friendship' => array('className'=>'Friendship')
);
Also, check typo errors like conditions instead of condition
Your table name might be the problem too. I had a table named "Class" and that gave cake fits. I changed it to something like Myclass and it worked. Class was a reserved word and Copy might be one too.