Hi i have two table friends and galleries I want to use CakePHP model Association between two table which Friend.friend_id = 1 and Gallery.user_id = 1
friends
id friend_id
-------------
1 5
2 1
3 6
galleries
id user_id photo
------------------------
1 1 photo1.jpg
2 6 photo2.jpg
3 5 photo3.jpg
Above two table i want to join. But i am unable to join. Please help me.
After lots of research finally i got my answer. This code helps to other-
//$user_id=$this->Session->read('Auth.User.id');
$user_id=1;
$this->Friend->bindModel(
array('hasOne' => array(
'Gallery' => array(
'className' => 'Gallery',
'foreignKey' => FALSE,
'conditions' => array('Friend.friend_id=Gallery.user_id'),
'type' => 'LEFT'
)
)
)
);
$this->Friend->bindModel(array('belongsTo' => array('User' => array('className' => 'User', 'foreignKey' => 'friend_id', 'conditions'=>array('Friend.user_id'=>$user_id)))));
$data = $this->Friend->find('all');
pr($data);
Related
I have an issue with using the find query in cakephp.
The problem is as follows :
I have to two models associated with each other..say MODEL 1 hasmany MODEL2.
Now I want to run a find query through model 1 in such a way that it has to fetch different number of results from Model2 Table as follows :
array(
0 => ( Model1 : { table contents }
Model2 : { array( 0 =>
1 =>
2 =>
3 =>
)
}
)
1 => ( Model1 : { table contents }
Model2 : { array( 0 =>
1 =>
2 =>
3 =>
4 =>
)
}
)
)
and so on. In other words Result of Model2 should vary but Model1 has fixed number of entries. I wanted to know what would be the most efficient ways to obtain the above mentioned result.
Further adding -
Consider the following table - Student (id, class, marks)
I want the following result:
There are 100 rows in the table. I want to fetch a total of 11 rows.
Condition => class is 'Computer'
First row should print details of student having id = 15;
Remaining rows should have any 10 ids ie. id != 15.
In total I need a total of 11 rows.
One more constraint is that user having id = 1 can be anywhere in the table.
This is a relation between two model. Hope it helps you....
Model-1:
var $hasMany = array(
'ProductOptionValue' => array(
'className' => 'ProductOptionValue',
'foreignKey' => 'product_option_id',
'conditions' => array('ProductOptionValue.is_active' => 1)
)
);
Model-2:
var $belongsTo = array(
'ProductOption' => array(
'className' => 'ProductOption',
'foreignKey' => 'product_option_id',
'fields' => array('id', 'product_option_name')
)
);
I'm a cakephp newbie, and I was ordered to use the 1.3 version.
I can't understand (and both guides and api docs don't tell it) how I could create an HABTM association in a POST request.
I'm trying to create a wine, that could be made of many vines. For example I'm creating a "soave" whine, that is made of "garganega" and "chardonnay" vines.
How should the POST params should be?
Given theses models
class Wine extends AppModel{
var $hasAndBelongsToMany = array(
'Vine' => array(
'className' => 'Vine',
'joinTable' => 'wine_vines',
'foreignKey' => 'wine_id',
'associationForeignKey' => 'vine_id',
'with' => 'WineVine',
),
);
}
class Vine extends AppModel{
var $hasAndBelongsToMany = array(
'Wine' => array(
'className' => 'Wine',
'joinTable' => 'wine_vines',
'foreignKey' => 'vine_id',
'associationForeignKey' => 'wine_id',
'with' => 'WineVine',
),
);
}
class WineVine extends AppModel{
var $name = "WineVine";
public $belongsTo = array("Wine", "Vine");
}
I tried a POST like this:
Array
(
[Wine] => Array
(
[denomination] => Soave DOP
[fantasy_name] =>
[kind] => White
)
[Vine] => Array
(
[0] => Array
(
[name] => garganega
)
[2] => Array
(
[name] => chardonnay
)
)
)
but it does not perform any inserts in vine table, only in wine.
Here's the log:
2 INSERT INTO `wines` (`denomination`, `fantasy_name`, `kind`, `modified`, `created`) VALUES ('', '', '', '2013-10-25 17:27:14', '2013-10-25 17:27:14') 1 55
3 SELECT LAST_INSERT_ID() AS insertID 1 1 1
4 SELECT `WineVine`.`vine_id` FROM `wine_vines` AS `WineVine` WHERE `WineVine`.`wine_id` = 2 0 0 1
5 SELECT `Vine`.`id`, `Vine`.`name`, `Vine`.`created`, `Vine`.`modified` FROM `vines` AS `Vine` WHERE 1 = 1 5 5 0
6 SELECT `Wine`.`id`, `Wine`.`denomination`, `Wine`.`fantasy_name`, `Wine`.`kind`, `Wine`.`created`, `Wine`.`modified`, `Wine`.`producer_id`, `WineVine`.`id`, `WineVine`.`wine_id`, `WineVine`.`vine_id`, `WineVine`.`created`, `WineVine`.`modified` FROM `wines` AS `Wine` JOIN `wine_vines` AS `WineVine` ON (`WineVine`.`vine_id` IN (1, 2, 3, 4, 5) AND `WineVine`.`wine_id` = `Wine`.`id`)
after saving the wine, try injecting its id into the data array
$this->data['Wine']['id'] = $this->Wine->id;
and then call an overloaded Model::saveAssociated() that will save all vines and update the join table by itself.
this overloaded method is described at:
http://bakery.cakephp.org/articles/ccadere/2013/04/19/save_habtm_data_in_a_single_simple_format
edit: sorry, that's for cake 2.x
i just realized 1.3 has no saveAssociated method
edit 2: but it does work in cake 1.3 if you change the last line of the saveAssociated method to
return parent::saveAll($data, $options);
I am trying to save an array like this
$myData = array(
'User' => array('id' => 17),
'Group' => array(
array('group_id' => 2),
array('group_id' => 3),
array('group_id' => 4),
array('group_id' => 5),
array('group_id' => 6)
)
);
In my HABTM join table (groups_users). I tried the following save calls, but none of them worked.
$this->User->save($myData);
$this->User->saveAssociated($myData);
$this->User->saveAll($myData);
$this->User->GroupsUsers->save($myData);
$this->User->GroupsUsers->saveAll($myData);
Before you ask: Yes, my associations are set-up correctly and I was able to save data by calling:
$this->User->GroupsUsers->saveAll(array(
0 => array(
'GroupsUsers' => array('user_id' => $id, 'group_id' => 1)
),
1 => array(
'GroupsUsers' => array('user_id' => $id, 'group_id' => 2)
)
));
BUT only one of both records are saved, although I set unique to false in the model's HABTM relationship definition.
Where is the error? Is the structure of my array invalid?
The problem is that your data array is incorrectly formatted.
Your Group model will probably have an id field, and your join model GroupsUser will have a group_id field.
So you need to change your group_id to id
try
$myData = array(
'User' => array('id' => 17),
'Group' => array(
'Group' => array(
0 => 2,
1 => 3,
2 => 4,
3 => 5,
4 => 6
)
)
);
Just to answer your question even if it's old.
You doesn't have to call your 'GroupsUsers' model in your saveAll call, this is precisely the goal of associating Models, cakePHP does that for you.
You should pass this array to a saveAll function on your User/Group model:
array{
array{
'User' => array {
'id' => 25
},
'Group' => array {
'id' => 2
}
}
array{
'User' => array {
'id' => 47
},
'Group' => array {
'id' => 2
}
}
}
Both your User and Group Models should have and HABTM relation with each other, so that you just have to do that:
From the User/Group controller:
$this->User/Group->SaveAll($myData);
From the User/Group Model:
$this->SaveAll($myData);
And that's it, the GroupsUsers table will save 2 records, by saving by yourself in the HABTM relation table, you are not using the power of cakePHP.
And the records in both User and Group tables will be created if the ID doesn't exist, updated if not.
The only reason to save in an HABTM table is if you have some extra information you want to save in this table such as a 'validated' fields if you want to validate a member after he asked to join a group for example.
This is my choices table
id | question_id | content
1 1 bee
2 1 fly
3 1 dog
4 2 cat
5 2 bat
6 2 wasp
and this is my questions table
id | content
1 question1
2 item2
This is what i did.With this I could display the question with its choices..what I want to do now, is to paginate it,more like 1 question per page.How to do this?Your help will be greatly appreciated.Thanks
$options['fields'] = array('questions.id','questions.content');
$options['joins'] = array(
array(
'table' => 'generated_exam_items',
'alias' => 'GenExamItems',
'type' => 'inner',
'conditions' => array(
'GenExamItems.generated_examination_id' => 25
)
),
array(
'table' => 'questions',
'alias' => 'Questions',
'type' => 'inner',
'conditions' => array(
'Questions.id = GenExamItems.questions_id'
)
),
);
$options['conditions']=array('GenExamItems.generated_examination_id' => 25,'Question.id=GenExamItems.questions_id');
$question_detail = $this->Question->find('all',$options);
$this->set('questions',$question_detail);
Someone please help me.!!I dont how to do it and im stuck in this for almos a week..
you can get using relation ship with each other model
as here i am just adding skeleton code you need to verify it to you actual code with real classname
In Question model write this relation
class Question extends AppModel {
public $hasMany = array(
'Choice' => array(
'className' => 'Choice',
)
);
And in Choice model you can define like
class Choice extends AppModel {
public $belongsTo = 'Question';
}
And in controller if you want to fetch for speacific Question with its choices you can write query like below
$question_detail = $this->Question->find('first', array(
'conditions' => array('Question.id' => $question_id)
));
let me know if i can help you more
Let's assume you have the correct associations on both models.
I'll show the code for just one question in the view.
If you use the automagic way cake provides (read the "Creating form elements" part)
In your controller, you have to get the choices
$this->set('choices', $this->Question->Choice->find('list',
array('conditions'=>
array('question_id'=>$your_question_id))));
And in your view, you have to do
echo $this->Form->input('choice_id', array('type'=>'radio'));
That should automatically display the choices as radios (not really sure what type of input you wanted)
If by some reason the automagic way doesn't work (be sure to check your model's associations if that happens), then you can pass the array of choices (get them as showed before on the controller) and pass it as a parameter
echo $this->Form->input('choice_id', array('type'=>'radio',
'options'=>$choices));
Note: If the radio labels are showing the ids instead of the content, you'll have to change the displayField of choices.
This what i did.It returns the question and corresponding choices.I hope I will be able to someone with this.Thank you.
public function take($id=null) {
$this->request->params['named']['page'] = (isset($this->request->params['page'])) ? $this->request->params['page'] : 1;
$options['fields'] = array('questions.id','questions.content');
$options['joins'] = array(
array(
'table' => 'generated_exam_items',
'alias' => 'GenExamItems',
'type' => 'inner',
'conditions' => array(
'GenExamItems.generated_examination_id' => 40
)
),
array(
'table' => 'questions',
'alias' => 'Questions',
'type' => 'inner',
'conditions' => array(
'Questions.id = GenExamItems.questions_id'
)
),
);
//$options['contains']='Choice';
$options['conditions']=array('Question.id = GenExamItems.questions_id');
$options['order']=array('rand(Question.id)');
$options['limit']=1;
$this->paginate=$options;
$data = $this->paginate('Question');
$this->set('questions',$data);
}
I have th e following model relationships:
Enquiry:
var $hasOne = array(
'SeminarAttendence' => array(
'className' => 'SeminarAttendence'
)
);
SeminarAttendence:
var $belongsTo = array(
'Enquiry' => array(
'className' => 'Enquiry',
'foreign_key' => 'enquiry_id',
)
);
my post data looks like this:
[Enquiry] => Array
(
[first_name] => joe
[last_name] => soap
[email_address] =>
[tel_home] =>
[tel_work] =>
[tel_cell] =>
)
[SeminarAttendence] => Array
(
[branch_id] => 178 // this has no table relation it's for a web service
)
I saveAll this in a controller:
$this->Enquiry->saveAll($this->data, array('validate' => 'first', 'atomic' => false
when I am done I get result like this in the SeminarAttendence
id branch_id enquiry_id
1 4 0
2 4 0
3 3 0
4 1 0
It worked fine on php5 yesterday, now when i ported it to our dev server (php4 ) it doesnt work?
It's not cakephp problem. because cakephp is made for php4, and works properly on php5. maybe something wrong with datebase, or config