Deep association findAll() with CakePHP 2 models - cakephp-2.0

I have models Trip, Investment, and Person. A single trip hasMany investments, and every investment belongsTo one Person. When I say $this->Trip->find('all'); I get:
Array (
[0] => Array (
[Trip] => Array (
[id] => 1
[date] => 2012-10-25 13:00:00
)
[Investments] => Array (
[0] => Array (
[id] => 1
[person_id] => 1
[investment_type_id] => 2
[trip_id] => 1
[investment] => 55
)
[1] => Array (
[id] => 2
[person_id] => 2
[investment_type_id] => 1
[trip_id] => 1
[investment] => 40
)
)
)
)
I would like each investment to include the information about the person represented by person_id (So their id, their name, etc). I've tried all levels of recursion on the find('all') lookup with no luck.

have you defined both ways of association in all models?
eg. Trip hasMany Investments AND Investment belongsTo Trip
Investment belongsTo Person AND Person hasMany Investments
also query should be
$this->Trip->find->("all", array("recursive" => 2));
other thing what could be problem is if all necessary models are loaded in your controller

See cakePHP model associations (retrieving data deeper) for an alternative solution:
Use
$this->YourModelname->recursive = 3;
before querying.

Related

Cakephp HABTM same model

I'm trying to figure out how to track the owners of real property. Investors specifically.
(I did spend hours researching and trying different things)
I'm using HABTM on the same model. (see below for why)
The difficulty I'm having is on the model->find. It only returns related entries if the id I'm searching for is in the first column of the relationship table.
In the entities table I have
1,Homer
2,Springfield Nuclear
3,Bart
In entities_relateds
2,1
2,3
(for the sake of argument, let's just assume that Bart grew up and went to work at the plant.
So both 1 & 3 are related to 2.)
If if do
$this->Entity->findById(2);
It looks great.
Array
(
[0] => Array
(
[Related] => Array
(
[id] => 2
[name] => Springfield Nuclear
[0] => Array
(
[id] => 1
[name] => Bart
)
[1] => Array
(
[id] => 3
[name] => Homer
)
)
)
)
However, if the values in the first row of entities_relateds are reversed...
1,2
2,3
I get
Array
(
[0] => Array
(
[Related] => Array
(
[id] => 2
[name] => Springfield Nuclear
[0] => Array
(
[id] => 3
[name] => Homer
)
)
)
)
It doesn't return the first row.
Doesn't matter if I do
$this->Entity->Related->findById(2);
It changes the array a bit, but still doesn't return the first row.
I'm wide open to alternate suggestions for how to solve this.
Thanks.
A bit more information here below.
Scenario:
It's pretty common to have people partner on deals and to own the property in either their own name, or any of several different companies. Partner A, Partner B, Company A, Company B. Any of these names could be on title, and really these are just aliases for the same 'group'.
So, I created a table called 'entities'. Each record can be either a real person, or a company. They share a lot of the same attributes, but most importantly, either type can be the legal owner of a piece of real property.
CREATE TABLE `entities` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
The relation table:
CREATE TABLE `entities_relateds` (
`entity_id` INT(11) NOT NULL DEFAULT '0',
`related_id` INT(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`entity_id`, `related_id`)
)
Model HATBM
App::uses('AppModel', 'Model');
class Entity extends AppModel {
public $hasAndBelongsToMany = array(
'Related' => array(
'className' => 'Entity',
'joinTable' => 'entities_relateds',
'foreignKey' => 'entity_id',
'associationForeignKey' => 'related_id',
'unique' => 'keepExisting'
)
);
}
I would recommend you to try setting the recursive of the model to 1 like:
$this->Entity->recursive = 1
and then try to do the find.
If this not works I'd give a shot to containable behavior which is even better than messing up with the recursivity of model.
If you choose to work with ContainableBehavior your find would end up like this:
$this->Entity->find('all',
array(
'conditions'=>array('id'=>2),
'contain'=>array('Related')
)
);
UPDATE 1: Added containable code.

Retrieve value from array in cakePHP

I want to know how to retrieve the values from array that is looking like that:
Array ( [0] => Array
( [Group] => Array
( [id] => 1
[name] => admin
[created] => 2013-04-15 14:13:19
[modified] => 2013-04-15 14:13:19
)
[Admin] => Array
( [0] => Array
(
[id] => 1
[email] => iman#yahoo.com
[username] => iman
[password] => 9e217e2039912c40b0f179f801e2d3e9fe8eb32e
[active] => 1
[mobile] => 01000000000
[created] => 2013-04-15 13:56:02
[modified] => 2013-04-15 14:44:59
[group_id] => 1
[tokenhash] => e2e1bbffc40d3f909594a268f0f3ec127fabe5c00e01c5f0644a1950aa37e6103ad18542a8731a2ad9ade283916281977677523098cd25a296116d078fbbc231
[image] => d
)...
Thanks.
What have you tried already?
As far as I can see based on the limited information provided, you have two options; access a value directly by providing the relevant keys or looping over the array.
Say you want to access the name of the first Group in the array, which I presume is stored in a variable (called $yourArray in this example):
$yourArray[0]['Group']['name']
The result will be 'admin'.
Looping would give you the benefit of retrieving all the group names (or any other value):
foreach ($yourArray as $value) {
//Output the Group name
echo $value['Group']['name'];
//Output the Admin email
echo $value['Admin'][0]['email'];
}
But the above is all fairly standard PHP stuff and not specific to CakePHP. It might be good to read up on the basics of PHP as well, as CakePHP adds another layer of abstraction by providing all kinds of framework conventions and convenience methods.

CakePHP HABTM recursive issue

To explain the issue I'm having, I'll use an example. Let's say that I'm building a system where students can sign up for an afterschool class, but an administrator has to approve the sign-up in order for it to be valid. So I have these models:
Calendar (belongs to "Teacher", hasAndBelongsToMany "Student")
Student (hasAndBelongsToMany "Calendar")
Teacher (hasMany "Calendar")
Now let's say I want to see a list of all of the unapproved sign-ups that are for ninth-graders. I want the list to include the calendar date, the student's name, and the teacher's name. I would do something like this:
$this->request->data = $this->Student->CalendarsStudent->find('all', array(
'conditions' => array(
'CalendarsStudent.is_approved' => null,
'Student.grade' => 9
)
));
The problem with the above code is that the returned array is missing the teacher's name:
Array
(
[0] => Array
(
[CalendarsStudent] => Array
(
[id] => 1274
[calendar_id] => 200
[student_id] => 872
[is_approved] =>
)
[Calendar] => Array
(
[id] => 200
[date] => 2012-12-17
[teacher_id] => 1
[total_slots] => 15
)
[Student] => Array
(
[id] => 872
[teacher_id] => 1
[first_name] => Billy
[last_name] => Smith
[grade] => 9
)
)
)
If I add 'recursive' => 2 to the find parameters, I get way too much information. $this->request->data[0]['Calendar'] will have [Teacher], which is what I want, but it will also have [Student], which I don't want. Also, $this->request->data[0]['Student'] will have subarrays that I don't want. It seems like Containable would fix this, but I can't get that to work either.
Any ideas?
Use CakePHP's [Containable Behavior]. It's amazing - easy to use and will return whatever you want it to.
Side note: If you're using "recursive" as anything other than -1 for ANYTHING, it should be a red flag. Containable is the absolute way to go as it lets you specify easily and exactly what data you want returned. Recursive will often cause memory issues and or other badness.
Best practice IMO: set $recursive = -1; in your AppModel.php and never set it to anything else...ever.

shorting an multideminsiol array according to its key value

i have any array
[0] => Array
(
[value] => 1
[label] => General
)
[1] => Array
(
[value] => 2
[label] => Wholesale Customers
)
[2] => Array
(
[value] => 3
[label] => Public Customers
)
[3] => Array
(
[value] => 4
[label] => Managers
)
its a multidimensional array in each index i have 2 key value & label is it possible to short out this array according to label (Z-A)
means
[0] => Array
(
[value] => 2
[label] => Wholesale Customers
)
[2] => Array
(
[value] => 3
[label] => Public Customers
)
[3] => Array
(
[value] => 4
[label] => Managers
)
[4] => Array
(
[value] => 1
[label] => General
)
using array shorting function in php think only short first index 0,1,2,3,4 or 4,3,2,1,0
or our own define pattern but when i have a lots of key in this array it not good practice to write each time a compare array so any way to short according to a particular key's value
in my desire output its take label which hold a value "wholesale customer" sift up & "Genral down bottom"
first i want to knwo any native function here in php to do this thing if not then how can i do this but not with loop re-ordering
function myfun($val1, $val2){
return ($val1["lable"]<$val2["lable"]) ? 0:1;
}
usort($myarr, "myfun");
print_r($myarr);
PHP function array_multisort() should probably do it for you. Have a look at this page for more info.
If not, then function uksort() will definitely work - as you are supplying your own comparison function for it. Have a look here.

How do i put this data in my DB?

i have an array in $this->data that looks like this:
Array
(
[Boeking] => Array
(
[start] => 25/12/2010
[end] => 26/12/2010
[centrum] => Brussels
[responsible] => Wouter
[email] => bla#bla.bla
[materials] => Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 8787
[4] => 5
[5] => 2572
[6] => 75
)
)
)
the fields in my DB are the same, so i have a table called 'boekings', with the fields 'start, end, centrum, responsible, email and materials'.
materials is a varchar(1000) so it should be long enough.
without CakePHP i used to do this with the serialize() function of php, but now i don't know the answer...
when i comment the line responsible for the materials array, it puts the data properly in my DB so there is no problem with my saveAll() method.
Thanx in advance guys!
Wouter
never mind got this working allready
http://cakeqs.org/eng/questions/view/how_do_i_put_this_data_in_my_db
thanx!

Resources