cakephp saveMany not saving the records in Table - cakephp

Here is my code
$users = array(
array( 'username' => $this->request->data['Shop']['admin_username'],
'password' => $this->request->data['Shop']['admin_password'],
'role' => 'admin',
'shop_id' => $shop_id,
'active' => 1
),
array( 'username' => $this->request->data['Shop']['manager_username'],
'password' => $this->request->data['Shop']['manager_password'],
'role' => 'manager',
'shop_id' => $shop_id,
'active' => 1
)
);
Debugger::dump($users);
//$this->User->create();
$this->User->saveMany($users);
where I am trying to save the 2 recoded in Database. But it's not working. I have also tried saveAll but i also did not work.

What does $this->User->saveMany($users); return?
Are there any validation rules you have inside your User Model?

Related

Model->find() conditions with no associated results

To stay simple, I have a User model which hasMany Post.
[User] id
[Post] id, user_id
How can I write a $this->User->find('all', array('conditions' => $conditions) to get all User who has no Post ?
assuming Post belongsTo User:
$this->User->Post->find(
'all',
array(
'fields' => array('User.id', 'user_id', 'COUNT(user_id) AS posts_count'),
'group' => 'user_id HAVING posts_count = 0'
)
)
Create one function inside User model and try below code: It will give all the User.id having no posts.
$options = array(
'conditions'=>array('Post.id is NULL')
'joins' => array(
array(
'alias' => 'Post',
'table' => ‘posts’,
'type' => 'LEFT',
'conditions' => array(
'Post.user_id = User.id',
),
)
),
'fields' => array('User.id')
);
$returnData = $this->find('list',$options);

Containable to do show deeper data or join table

I have 3 tables: projects, project_reminder_users, project_types.
The relations is as follow:
Project => belong to => ProjectType
hasMany => ProjectReminderUser
ProjectReminderUser => belong to => Project
ProjectType => hasMany => Project
I get all data based on who assigned(ProjectReminderUser) by this
$this->Project->ProjectReminderUser->Behaviors->load('Containable');
$this->paginate = array(
'ProjectReminderUser' => array(
'limit' => $limit,
'contain' => array(
'Project' => array(
'ProjectComment',
'ProjectFile',
),
'User'
),
'conditions' => array(
'User.group_id' => $this->Session->read('Auth.User.group_id'),
'ProjectReminderUser.user_id' => $this->Session->read('Auth.User.id'),
'Project.project_status_id' => PROJECT_STATUS_OPEN,
),
'order' => 'Project.due_date',
)
);
$this->set('myTasks', $this->paginate('ProjectReminderUser'));
and the result look like this
array(
'ProjectReminderUser' => array(
'id' => '96',
'user_id' => '1',
'project_id' => '46'
),
'Project' => array(
'id' => '46',
'project_type_id' => '9',
'contact_id' => null,
'company_id' => null,
'subject' => 'Test Modified Field',
'description' => 'Test Modified Field',
'ProjectFile' => array(
(int) 0 => array(
'id' => '19',
'project_id' => '46',
'user_id' => '6',
'file_path' => '46_bhbinary_xmm_1728.jpg',
'notes' => null,
'created' => '2013-11-26 18:37:49'
),
),
'ProjectComment' => array(
)
),
'User' => array(
'password' => '*****',
'id' => '1',
'group_id' => '1',
'email' => 'xxx#xxxxx.com',
'first_name' => 'xxxx',
'deleted' => false,
'displayName' => 'xxxxx'
)
)
In the result There is data for Project.project_type_id, but I would like to have more detail of that. So I can show it as name instead of number. maybe like ProjectType.name instead.
How can I achieve this, so I can sort it in the view? something like this
$this->Paginator->sort('ProjectType.name', 'Type');
The problem is that Paginator doesn't play nice with deep model associations. I think though if rather than using Cake's methods for doing model associations, you instead do your joins manually, you may be able to work out the sorting as you want. See the below discussion.
http://sinkpoint.railsplayground.net/cakephp-pagination-deep-sort-and-habtm/
Worst comes to worse, you may have to also rewrite the model's paginate function to deal with sorting how you need it to.
How about
'contain' => array(
'Project' => array(
'ProjectComment',
'ProjectFile',
'ProjectType',
),
'User'
),
Looks like you did not contain "ProjectType"

CakePHP - model belongsTo 2 different model

I'm making a Photo model, is it a good practice to make it belong to multiple models such as User, Place, etc?
Place also belongs to User
So here is my fields for Photos.
id
owner_id
type (an enum of the different models such as users and places)
Here is the belongsTo in PhotoModel that I have
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'owner_id',
'conditions' => array('Photo.type' => 'user'),
'fields' => '',
'order' => ''
),
'Place' => array(
'className' => 'place',
'foreignKey' => 'owner_id',
'conditions' => array('Photo.type' => 'place'),
'fields' => '',
'order' => ''
)
);
Or is it better to just create separate models such as UserPhoto, PlacePhoto etc?
Right now with this approach, I'm sometimes seeing dbo error when I set recursive to 2.
Thanks,
Tee
This approach can work, although if you set recursive to 2, the clearest solution is to create and/or destroy associations on the fly in such queries.
If in future you are going to use UserPhoto and PlacePhoto model, then it will be better to create separate models for them. So that you can customize those models later on. Or otherwise if you are using those models rarely then you can particularly bind those models in to your controller's method.
$this->User->bindModel(array('belongsTo' => array(
'User' => array(
'className' => 'User',
'foreignKey' => 'owner_id',
'conditions' => array('Photo.type' => 'user'),
'fields' => '',
'order' => ''
),
'Place' => array(
'className' => 'place',
'foreignKey' => 'owner_id',
'conditions' => array('Photo.type' => 'place'),
'fields' => '',
'order' => ''
)));

Login Errors not sure why

I'm using a login with a scope to ensure that the user account is active. If the login fails how can i tell if it failed because the email was not matched or if the accounts wasn't activated?
Also, i didn't understand all of the documentation in the cakephp cookbooks, could you please look at my auth section in my components array?
The Email field in the html table and sql table are called 'AccountEmail'
The Password field in the html table and sql table are called 'AccountPassword'
The row in the sql table for active accounts is called 'AccountActive' and is an int type with a value of 0 if the user is not active and 1 if it is active.
'Auth' => array(
'logoutRedirect' => array('controller' => 'Accounts', 'action' => 'login'),
'authError' => 'You can\'t Access That Page',
'authorize' => array('Controller'),
'fields' => array('AccountEmail' => 'AccountEmail', 'AccountPassword' => 'AccountPassword'),
'scope' => array('AccountActive' => '1')
)
You're missing which authentication handler to use and your fields configuration was wrong.
I'll assume you want to use a form to login:
/**
* Auth component configuration
*/
public $components = array(
'Auth'=> array(
'logoutRedirect' => array(
'controller' => 'Accounts',
'action' => 'login'
),
'authError' => 'You can\'t Access That Page',
'authorize' => array('Controller'),
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'AccountEmail',
'password' => 'AccountPassword'
),
'scope' => array('AccountActive' => '1')
)
)
)
);

CakePHP multiple model conditions in find() with HABTM

My schema has the following relations:
User hasMany Transaction belongsTo User
Item hasMany Transaction belongsTo Item
User hasManyAndBelongsTo Item using Transaction as join table
I'd like to return all items of a given item symbol that belong to a given user id. I'm able to retrieve all the items that belong to the user with
$this->User->find('all', array( 'conditions' =>
array( 'User.id' => $userId ) ) )
and I'm able to retrieve all the Items with a given item name with
$this->Item->find( 'all', array( 'conditions =>
array( 'Item.symbol' => $itemSymbol ) );
but if I try to use the condition array( 'Item.symbol' => $itemSymbol, 'User.id' => $userId ) on $this->Item->find(), $this->Item->User->find(), $this->User->find(), or $this->User->Item->find(), I get either the error
SQL Error: 1054: Unknown column 'Item.id' in 'where clause'
or
SQL Error: 1054: Unknown column 'Item.symbol' in 'where clause'
I've devoured HABTM in all versions of the cookbook and read tens of forum / SO posts about it, but I haven't had any luck in forming this query.
Relevant Info:
// User.php associations
// a user hasMany transactions
var $hasMany = array('Transaction' =>
array('className' => 'Transaction',
'order' => 'Transaction.created DESC', // order by descending time of transaction
//'limit' => '1', // change this if we need more, for example, if we need a user transaction history
'foreignKey' => 'user_id',
)
);
// a user hasAndBelongsTo items through transactions
var $hasAndBelongsToMany = array('Item' =>
array('className' => 'Item',
'joinTable' => 'transactions',
'foreignKey' => 'user_id',
'associationForeignKey' => 'item_id',
'order' => '',
'limit' => '',
'unique' => true,
'finderQuery' => '',
'deleteQuery' => '',
)
);
// Item.php associations
var $hasMany = array('Transaction' =>
array('className' => 'Transaction',
'order' => 'Transaction.created DESC',
//'limit' => '1', // change this if we need more, for example, if we need a item transaction history
'foreignKey' => 'item_id',
)
);
// a item hasAndBelongsTo users through transactions
var $hasAndBelongsToMany = array('User' =>
array('className' => 'User',
'joinTable' => 'transactions',
'foreignKey' => 'item_id',
'associationForeignKey' => 'user_id',
'order' => '',
'limit' => '',
'unique' => true,
'finderQuery' => '',
'deleteQuery' => '',
)
);
// Transaction.php associations:
var $belongsTo = array('User', 'Item');
You're looking for the Containable behavior; e.g.
// app_model.php
var $actsAs = array(
'Containable'
);
I'm assuming User extends AppModel, so Containable will be set for the child (User). Now, in your controller, conditions for the related class can be placed in the 'contain' key of the second argv of find(); e.g.
// users_controller.php
$this->User->find('first', array(
'conditions' => array('User.id' => $userId),
'contain' => array(
'Item' => array(
'conditions' => array('Item.symbol' => $itemSymbol)
)
)
);
Cake will find the matching User and retrieve matching Items (with the same user_id and the Item.Symbol specified. But be very careful to use 'contain' => array() when it is not required, otherwise Cake will retrieve all of the defined associations, which will tax your database.

Resources