Yii Relational Query with 'through' - database

Good evening,
In this page (http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through) it's described how to get all comments for all users of a particular group using 'through':
class Group extends CActiveRecord
{
...
public function relations()
{
return array(
'roles'=>array(self::HAS_MANY,'Role','group_id'),
'users'=>array(
self::HAS_MANY,'User',array('user_id'=>'id'),'through'=>'roles'
),
'comments'=>array(
self::HAS_MANY,'Comment',array('id'=>'user_id'),'through'=>'users'
),
);
}
}
How can I do exactly the opposite? That is, get the group of the user who made a particular comment (Comment Model basically).
So far, I'm not even able to reach 'role' table:
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'roles'=>array(self::HAS_MANY, 'Role', array('id'=>'user_id'), 'through' => 'user') // shouldn't it join User.id to Role.user_id ?
It's raising the following error: 'Column not found: 1054 Unknown column 'user.user_id' in 'where clause'. And it seems related to the first line, not the second...
Any ideas?
Sincerely,
Apidcloud

As you want to get the group of the user who made a particular comment. You have to add these relation in the comment model.
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'roles'=>array(
self::HAS_ONE,'Role',array('id'=>'user_id'),'through'=>'user'
),
'group'=>array(
self::BELONGS_TO,'Group','group_id','through'=>'roles'
)
);
}
And view file you can get group name like this.
<?php echo CHtml::encode($data->group->name); ?>
Hope this will help you.

Related

Cakephp 2 - Most simple associations

I'm facing trouble telling cake the most simple associations.
I have two Models:
CoreUser.php
CoreRole.php
.
One User has one Role.
How to assign that in cake? (HasOne or BelongsTo? => When to choose what?)
What to put in what Model? I tried both and ever end up with a recursion-error or it is just not working.
My SQL-Tables:
(tbl) core_users [id,username,password,role_id]
(tbl) core_roles [id,name]
My Models:
class CoreUser extends AppModel {
public $hasOne = array(
'Role' => array(
'className' => 'CoreRole',
'foreignKey' => 'id'
)
);
}
class CoreRole extends AppModel {
public $belongsTo = array(
'User' => array(
'className' => 'CoreUser',
'foreignKey' => 'role_id'
)
);
}
=> Can you give me the correct code i need to insert into one of both (or both) models to tell cake about the relationship?
Thanks in advance
Theoretically, there are two things you need to think about, one of them being non-Cakephp specific.
A. Relationships: A relationship is always bidirectional. When determining the relationship between two Models/Objects/Tables, you always ask two questions:
How many instances of B are related to one instance of A?
How many instances of A are related to one instance of B?
You've said, One user has one Role. However, One Role has how many Users related to it? That will tell you the complete relationship between a User and a Role. (Apologies for the digression but this is important and I'm referencing this book.)
B. Difference between hasMany and belongsTo:
This is determined based on the direction of traversing a relationship.
Based on point A, say you've determined that:
One User has one Role but One Role has many Users.
Now when you are in the User's model trying to fetch related Role data, you need to define the following in the User model:
class CoreUser extends AppModel {
public $belongsTo = array(
'Role' => array(
'className' => 'CoreRole',
'foreignKey' => 'role_id'
)
);
}
But when you are in the Role's model and trying to fetch related User data, you will need to define the following in the Role model:
class CoreRole extends AppModel {
public $hasMany = array(
'User' => array(
'className' => 'CoreUser',
'foreignKey' => 'role_id'
)
);
}
For a full discussion refer to this answer.

CakePHP Save newly created ID in Parent ID field of self assoc model

I have a parent/child self association table where when the id = parent_id, that id is it's own parent. However I'm having trouble saving data into my table from the add action/view
From add.ctp view - when adding a new record, I select a parent_id from the drop down box and enter a name.
<?php
echo $this->Form->input('parent_id', array('empty' => 'No Parent'));
echo $this->Form->input('name');
?>
If user selects "No Parent" this means I would like the parent_id = id where id is the unique ID automatically created in DB at time it is saved.
This is what is passed into $this->request->data when 'No Parent' is selected.
array(
'Item' => array(
'parent_id' => '',
'name' => 'testname'
)
)
I have tried to set the parent_id = id in the beforeSave but since id does not yet exist, there is nothing to assign parent_id to. I have also tried calling the "parent" model save first and saveAll in the controller but those don't work either.
Controller
public function add() {
if ($this->request->is('post')) {
$this->Item->create();
//have tried calling parent model in self association first but
//if ($this->Item->ParentItem->save($this->request->data)) {
if ($this->Item->saveAll($this->request->data)) {
$this->Session->setFlash(__('The item has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The item could not be saved. Please, try again.'));
}
}
Item.php / Model relationship
public $belongsTo = array(
'ParentItem' => array(
'className' => 'Item',
'foreignKey' => 'parent_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $hasMany = array(
'ChildItem' => array(
'className' => 'Item',
'foreignKey' => 'parent_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
)
);
How can I take an ID that is just created/saved and save that to another field, in this case parent_id?
UPDATE:
I have been working on this some more and I have used getInsertId() to get the last inserted Id and I am trying to save that into the parent_id, but there is something that prevents this. I have removed all model validation to make sure it wasn't that. But is there something in Cake (or my association setup) that does not allow parent_id = id (i.e. a row is it's own parent?
This is the latest code in my add action... This saves a row to the DB, but w/o a parent_id. I then try to edit using the add action and set the parent_id = id, but even the edit wont allow a save.
public function add() {
if ($this->request->is('post')) {
$this->Item->create();
if ($this->Item->save($this->request->data)) {
$last_id = $this->Item->getInsertId();
$this->Item->saveField('parent_id', $last_id);
$this->Session->setFlash(__('The item has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The item could not be saved. Please, try again.'));
}
}
I have also tried calling $this->Item->ParentItem->save(), saveAll, 'deep' => true, but still nothing is allowing me to update the parent_id column. A row ge
Thanks in advance
In Your model of association You can set foregin_key to parent_id, and will be automatic filled
So the problem I was having... trying to set a parent_id = id (making id it's own parent basically) in a self join model is due to this piece of code in my Model file
public $actsAs = array('Tree');
After reading through the Tree Behavior again, I realized that $this->Model->save (or saveField) does not really work well with Tree structures and updating parent IDs. Should use the behaviors functions instead form my understanding. Also the TreeBehavior expects some parent_ids to be null (at least top level parent_ids), so if I were to leave this as a tree, the ids with a null parent_id would be considered the parent.
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html
"The parent field must be able to have a NULL value! It might seem to work if you just give the top elements a parent value of zero, but reordering the tree (and possible other operations) will fail."
So I need to decide if I want to use tree behavior or have simple parent/child relationship without using Tree... think I will do the later as I don't have a need for multilevel tree, just a parent and one level of children.
Thanks for replies.

Cake Relations with diffent name

I got a Table Users and a Table Groups. Every group has one GroupLeader.
So the field i use in is groupLeader ($hasOne) which contains a foreign key of users.
I cant manage to get that relation. So my question is, how to define a relation on a field with a diffent name.
thanks for a hint.
endo
You model should looks:
class Group extends AppModel
{
public $name = 'Group';
public $belongsTo = array('GroupLeader' => array(
'className' => 'User',
'foreignKey' => 'groupLeader'
)
);
}
Try with the above code. And ask if it is not worked for you.

How do I load associated models and save related data in CakePHP?

I am setting up a user/group system that allows users to send requests to join a group.
I can't seem to load the associated model and add a row. It's really really really difficult to resist the urge to just use $this->query() and be done with it... but I'm trying to learn the Cake conventions and do things the right way.
In my group model's function for handling group join requests:
$this->loadModel('GroupRequest');
$this->data = array('GroupRequest' =>
array('user_id' => $uid, 'group_id' => $gid));
if($this->GroupRequest->save($this->data)){ echo 'save success'; }
else { echo 'save fail'; }
Here are the errors I get when I run this:
Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'loadModel' at line 1 [CORE/cake/libs/model/datasources/dbo_source.php, line 684]
Query: loadModel
Notice (8): Undefined property: Group::$GroupRequest [APP/models/group.php, line 124]
Fatal error: Call to a member function save() on a non-object in /home/wxworksmat/sspot3/app/models/group.php on line 124
I also tried using App::import:
App::import('Model','GroupRequest');
I don't get any SQL errors importing the Model this way, but it still doesn't work. I get the following error on the save() or create() call:
Fatal error: Call to a member function save() on a non-object in /home/wxworksmat/sspot3/app/models/group.php on line 124
You are confusing controller and model methods
$this->loadModel()
is a controller method and can only be used there.
You should always use
$this->ModelName = ClassRegistry::init('ModelName');
everywhere else
I might be wrong, and please excuse me if I'm wrong, but it looks like you don't understand the concept of the framework very well. It is difficult to answer your question without giving you a complete tutorial.
This said, everything relies on model associations. If it's done correctly, things are getting easy. You should read:
Associations: Linking Models Together
Once you have your models correctly linked, you will be able to save the primary model, as well as the related model, very easily.
Saving Related Model Data (hasOne, hasMany, belongsTo)
As I understand, you are trying to do this from inside a model?
class GroupRequest extends AppModel {
public function associate($user, $group) {
$data["GroupRequest"] = array("user_id" => $user, "group_id" => $group);
$this->save($data);
}
}
Then in your Controller (assuming group_requests_controller)
$this->GroupRequest->associate($user, $group);
If you're calling this from another controller you would loadModel first
$this->loadModel("GroupRequests");
$this->GroupRequest->associate($user, $group);
However, if you're doing all of this from within GroupRequests controller you should be able to save directly, without making a separate method for it
public function add() {
$this->GroupRequest->create();
$this->GroupRequest->save($this->data); #for < 2.0
}
Your view should be something like
<?php
echo $this->Form->create("GroupRequest");
echo $this->Form->input("user_id");
echo $this->Form->input("group_id");
echo $this->Form->end("Submit");
?>
The problem I had was that I didn't have the correct model association declarations at the top of my model.
Now I have:
group.php
var $hasMany = 'GroupRequest';
group_request.php
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public function new_request($user, $group) {
$data["GroupRequest"] = array("user_id" => $user, "group_id" => $group, 'status' => 'pending');
if($this->save($data)){ return true;} else {return false;}
}
Now because everything is set up CORRECTLY... I can do this in my group.php model:
$this->GroupRequest->new_request($uid,$gid)
As an added bonus, because the assocations are populating properly, when I do $this->find in my group or user model, now all the related GroupRequest entries show up. Bonus data FTW.

how to create a chain select form in cakephp

My business directory application calls for 3 chained select boxes, and I'm using cakephp to build this application.
The hierarchy and order of choices for the sections is this:
1 - business group
2 - business type
3 - city (included in table customer)
The relationships are:
customer HABTM business types
business groups have many business types
business types have one business group, HABTM customers
I have searched for jquery plugins that help with this, and found one by Remy Sharp, but it doesn't have the more complex relationships I have.
http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/
What I imagine happening is the first selection box (business groups) is pre-populated and once a selection is made, an event listener send a message that filters the second selection box, and the same for the third.
What I don't know is how to structure the search action based on the event listener.
Any advice or am I way off base?
As always, I come to the well for help.
Much appreciated.
Paul
Thanks very much Nick, I've read many of your posts I really appreciate your response.
I've followed your instructions but have run into problems. I've tried my best to resolve them but haven't figured it out.
This is what I've done so far:
1) created 'chained' actions in both the business_type and business_directory (renamed customer to business directory, which is more appropriate.)
business type chained action:
function chained($business_group_id) {
$business_types = $this->BusinessType->find('list', array(
'conditions' => array( 'BusinessType.business_group_id' => $business_group_id)
));
$this->set('business_types', $business_types);
}
business directory chained action:
function chained($business_type_id) {
$business_directories = $this->BusinessDirectory->bindModel(array( 'hasOne' => array('business_directories_business_types' )));
$business_directories = $this->BusinessDirectory->find('all', array(
'fields' => array( ' BusinessDirectory.city'),
'conditions' => array( 'business_directories_business_types.business_type_id' => $business_type_id)
));
$this->set('business_directories', $business_directories);
}
I did find that with a HABTM relationship, using find 'list' didn't create the join query, whereas find 'all' did.
2) I then created a search action in the business directory and corresponding view.
For the business groups I created a getList action to populate the option list in the search form:
function getList() {
return $this->BusinessGroup->find('list');
}
In the search view, I've added the javascript for the chain select:
<script type="text/javascript">
<!--
$(function () {
var group = $('#businessGoup');
var type = $('#businessType');
var city = $('#businessDirectoryCity');
type.selectChain({
target: city,
url: '../business_directories/chained/'+$(this).val(),
data: { ajax: true, anotherval: "anotherAction" }
});
group.selectChain({
target: type,
url: '../business_types/chained/'+$(this).val()
}).trigger('change');
});
//-->
</script>
And the form:
create('business_directories', array('action'=>'/search_results')); ?>
input('business_group_id',
array( 'type' => 'select',
'id' => 'businessGoup',
'empty' => '-- Select Business Group --',
'multiple' => true,
'options' => $this->requestAction('/business_groups/getList' ),
'label' => 'Business Group'));
?>
input('business_type.id',
array( 'type' => 'select',
'id' => 'businessType',
'empty' => '-- Select Business Type --',
'multiple' => true,
'options' => 'none selected',
'label' => 'Business Type'));
?>
input('business_directories.id',
array( 'type' => 'select',
'id' => 'businessDirectoryCity',
'empty' => '-- Select City --',
'multiple' => true,
'options' => 'options',
'label' => 'City'));
?>
end('Search'); ?>
When I test the business type chain function, /business_types/chained/1, everything works.
But when I test the search view, I get a javascript alert error. Then when I check firebug, I get the following two errors:
Warning (2): Missing argument 1 for BusinessTypesController::chained() [APP\controllers\business_types_controller.php, line 71]
Notice (8): Undefined variable: business_group_id [APP\controllers\business_types_controller.php, line 73]
Any additional help with this is very much appreciated.
Thanks, Paul
What you need is to have 2 actions in the controllers (business_type and customer).
each action should look like this. In that case for the business type
function chained($parent_id){
$business_types = $this->BusinessType->find('list', array('conditions'=>'BusinessType.business_group_id'=>$parent_id));
$this->set('business_types', $business_types);
}
of course you need also view for that action which will format the values in the proper format for the chained select.
For Business group you need to show all values directly so no ajax is needed.
The Customer controller's action is similar, but you need to select cities of all related customers.
Then with the chained select you need to set the proper elements and set the proper actions which need to be called.
i.e.:
$('#id-of-the-business-group').selectChain({
target: $('#id-of-the-business-type-field'),
url: '/business_types/chained/'+$(this).val()
});

Resources