In the CakePHP Documentation they implement this as below !!
class Message extends AppModel {
public $belongsTo = array(
'Sender' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'Recipient' => array(
'className' => 'User',
'foreignKey' => 'recipient_id'
)
);
}
and
class User extends AppModel {
public $hasMany = array(
'MessageSent' => array(
'className' => 'Message',
'foreignKey' => 'user_id'
),
'MessageReceived' => array(
'className' => 'Message',
'foreignKey' => 'recipient_id'
)
);
}
But this didn't work with me !!
and give me some errors that there's some tables in the User Model is not found !!
this will work just if I use the name of HasMany to the same name of the Model !!
After some googling searchs with fail !!
I just go to the easiest ways !!
public $hasMany = array(
'Follow_me'=>array(
'className'=>'Friend',
'foreignKey'=>'user_to' ,
) ,
'Follow_them'=>array(
'className'=>'Friend2',
'foreignKey'=>'user_from'
) );
this is the User Model
and
Class User
now the Friend Model
public $belongsTo = array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_from' ,
) ,
);
the table of friends will be
id || user_from || user_to || created || modified
now with the easiest way !!
Create a new Model Class with the name Friend2
public $useTable = 'friends';
public $belongsTo = array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_to' ,
) ,
);
now !!
when you fetch from the User Model the Data will be like that
array(
(int) 0 => array(
'User' => array() ,
'Follow_me' => array() ,
'Follow_them' => array() ,
'Some_Other_Relations_Goes_here' => array()
) )
Hope this will Help you All
Related
I would like to bind models, mostly because the datasources change from one model to the other. Let's say I have the following query :
SELECT ext.col1, ext.col2, ext.col3, COUNT(*) Link Count
FROM `external.`Media` ext
INNER JOIN `internal`.`links` l ON ext.someId = links.id
INNER JOIN `internal`.tags t ON l.tag_id = t.tag_id
WHERE t.parent_tag_id = 1098
AND t.metadata = 'someValue'
GROUP BY ext.col1, ext.col2, ext.col3
So I have 3 models from which data is coming from. Currently I have the following in the Media model..
public $belongsTo = array(
'Links' => array(
'className' => 'Links',
'foreignKey' => 'someId',
),
'Tag' => array(
'className' => 'Tag'
)
);
Then in the other models :
Tag Model
public $useTable = "tags";
public $name = 'Tag';
public $hasAndBelongsToMany = array(
'TagLink' => array(
'className' => 'TagLink',
'foreign_key' => 'tag_id',
'conditions' => array(
'Tag.parent_tag_id' => 1098
)
)
);
Link Model
public $useTable = "tag_links";
public $name = 'TagLink';
public $hasAndBelongsToMany = array(
'Tag' => array(
'className' => 'Tag',
'foreign_key' => 'tag_id'
)
);
Then back in the Media model , I use the find expecting to have the model binding set up :
return $this->find("all", array(
'conditions' => array(
'Tag.metadata' => $username
)
));
This generates an error :
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Tag.metadata' in 'where clause'
I am assuming that this is happening because the table is not found
[SQL Generated]
SELECT `Media`.`media_id`, `Media`.`mediatype`, `Media`.`created`, `Media`.`active_flag`,
`Media`.`mediafile`, `Media`.`fallbackfile`, `Media`.`setupId`, `Media`.`externalId`,
`Media`.`width`, `Media`.`height`, `Media`.`brands`, `Media`.`languages`, `Media`.`products`,
`Media`.`projects`, `Media`.`affiliates`, `Media`.`description`, `Media`.`linking_code` FROM
`external`.`ext_media_gallery` AS `Media` WHERE `Tag`.`metadata` = 'testuser' AND
`MediaGallery`.`active_flag` = 'active' AND ((FIND_IN_SET('testuser', `Media`.`affiliates`)) OR
(`Media`.`affiliates` = ''))
This basically shows that the binding is incorrect/not happening
Basically I want to replace the following to avoid using joins on the fly since these would need to apply for every query.. hence the model binding..
This works for me, but I want to convert it to do it using model binding :
return $this->find("all", array(
"joins" => array(
array(
"table" => "internal.links",
"alias" => "Link",
"type" => "INNER",
"conditions" => array(
"Link.id = Media.someId"
)
),
array(
"table" => "internal.tags",
"alias" => "Tag",
"type" => "INNER",
"conditions" => array(
"Tag.tag_id = Link.tag_id",
"Tag.parent_tag_id = 3214",
"Tag.metadata" => $username
)
),
)
));
sorry for my english and i'm new using CAKEPHP 2.3
i get a problem using model association where i can't get "joined data" ( i understand that cakephp get automatically joined data if models are set good , obviously i make it wrong )
I have 2 tables in my database:
departements (with the following columns)
-id
-name
-region_id ( region_id is a foreign key on regions(id) )
regions (with the following columns)
-id
-name
i make two models in cakePhp:
Region.php
<?php
class Region extends AppModel {
var $name = 'Region';
var $actsAs = array( 'Containable' );
public $hasMany = array(
'Departement' => array(
'className' => 'Departement',
'foreignKey' => 'region_id',
'dependent' => false
)
);
}
?>
Departement.php
<?php
class Departement extends AppModel {
var $name = 'Departement';
var $actsAs = array( 'Containable' );
public $belongsTo=array(
'Region' => array(
'className' => 'Region',
'foreignKey' => 'region_id',
'dependent' => false
)
);
}
?>
in a another controller where i need departements and regions, i tryed many thinks but after yours i need your help please !!!
i make this :
first attempt:
<?php
class SignalementsController extends AppController {
public $helpers = array('Html', 'Form');
var $name = 'Signalements';
var $uses = array('Signalements','Regions','Departements','Communes');
public $recursive = 4;
public function index() {
$departements = $this->Departements->find('all');
$this->set('departements', $departements);
}
}
who output in the index view:
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'name' => 'AIN',
'region_id' => '82'
)
),
(int) 1 => array(
'Departements' => array(
'id' => '10',
'name' => 'AUBE',
'region_id' => '21'
)
)
...
)
but there is no region joined automatically
second attempt: i change the find models from
$regions = $this->Regions->find('all');
$this->set('regions', $regions);
who output :
array(
(int) 0 => array(
'Regions' => array(
'id' => '11',
'name' => 'ILE-DE-FRANCE'
)
), ... );
but there is no departements joined automatically
last
$fields=array('Region.id','Region.nom','Departement.id','Departement.nom');
$all= $this->Regions->Departements->find('all',$fields);
/* or all this not working as execpted
$all= $this->Departements->Regions->find('all',$fields);
$all= $this->Departements->find('all',$fields);
$all= $this->Regions->find('all',$fields);
*/
$this->set('all', $all);
i try to get the regions data inside each departemts for exemple like this
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'nom' => 'AIN',
'region' => array( 'id' => '82', 'nom' => 'POITOU-CHARENTES')
)
),
but i get only this :
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'nom' => 'AIN',
'region_id' => '82'
)
),
If you have any idea please leave it
thank you very much
You are using Containable behaviour in your model, so try the find with this:
$departements = $this->Departement->find('all', array('contain' => 'Region'));
Also the maximum level for recursive is 2, setting it to 4 (or 1000) has the effect of 2.
Your ID is of type varchar and should be int.
Also, here is a stripped down version of your code
Region.php
<?php
class Region extends AppModel {
var $actsAs = array( 'Containable' );
public $hasMany = array( 'Departement' );
}
?>
Departement.php
<?php
class Departement extends AppModel {
var $actsAs = array( 'Containable' );
public $belongsTo=array( 'Region' );
}
?>
<?php
class SignalementsController extends AppController {
public $helpers = array('Html', 'Form');
var $uses = array('Signalements','Regions','Departements','Communes');
public function index() {
$this->Departement->recursive = 1;
$departements = $this->Departements->find('all');
$this->set('departements', $departements);
}
}
index.ctp
<?php print_r($departements); ?>
What does it give you?
I keep getting a "Call to a member function on a non-object" error in the index function of one of my controllers. Here is the code:
class ModulesController extends AppController {
public $uses = array('Module', 'User');
public $scaffold;
function index() {
if ($this->request->is('get')) { //Technically unecessary but good practice
$email = AuthComponent::user('email');
$user = $this->Module->User->findByEmail($email);
//Code omitted
}
}
And this is my Module model:
class Module extends AppModel {
public $name = 'Module';
public $hasMany = array(
'Slide' => array(
'className' => 'Slide',
'foreignKey' => 'module_id',
'order' => 'Slide.position ASC' //Let's make sure that name is correct
));
public $belongsTo = array(
'Creator' => array(
'className' => 'User'));
public $hasAndBelongsToMany = array(
'OUser' => array(
'className' => 'User',
'joinTable' => 'modules_users',
'foreignKey' => 'module_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
));
} //Unnecessary code omitted
And this is the code for my user model:
class User extends AppModel {
public $name = 'User';
public $uses = 'users';
public $hasMany = array(
'OModule' => array( //Owner of Modules
'className' => 'Module',
'foreignKey' => 'user_id',
'order' => 'Module.created DESC'
));
public $hasAndBelongsToMany = array(
'Module' => array(
'className' => 'Module',
'joinTable' => 'modules_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'module_id',
'unique' => 'keepExisting',
));
} //Unnecessary code omitted
It is worth mentioning that User and Module have both a belongsTo and a HABTM relationship, so User has the aliases Creator and OUser respectively. In the code above, the findByEmail is trying to use the Creator relationship, but that gives me the same error.
My question is, how do I call the findByEmail() method without error?
Change:
$user = $this->Module->User->findByEmail($email);
To:
$user = $this->User->findByEmail($email);
Voila!
Reason:
Somehow, there is either 1) no relationship between Module and User, 2) a mistake in the relationship, or 3) your using an alias for either or both of them so that using Module->User wouldn't be correct.
You're loading the 'User' model anyway though, so there's no reason to go through the Module model to access it - just access it directly (like example above).
I know the solutions is simple and might have something to do with the Containable behavior but I can't get it working. Without all the tries
This is the case. I'd like to display the Event details of an Event (eg. a conference). Each event takes place in a EventVenue and each EventVenue is located in a Country.
So in the Country Model the following is present:
public $hasMany = array(
'EventVenue' => array(
'className' => 'EventVenue',
'foreignKey' => 'country_id'
))
In the EventVenue model a BelongsTo association is made
public $belongsTo = array(
'Country' => array(
'className' => 'Country',
'foreignKey' => 'country_id'
))
And in the Event model a hasOne association is made
public $hasOne = array(
'EventVenue' => array(
'className' => 'EventVenue',
'foreignKey' => 'event_id',
))
What I want is to display the country name on the page that is renderd in the EventsController. I do get all the Event and EventVenue data but the associated Country for the venue is not retrieved.
The data is retrieved in the following way
$item = $this->Event->findBySlug($slug);
How can I also get the country name (eg. Netherlands) retrieved from the database? I tried something like this but that did not work:
$item = $this->Event->findBySlug($slug,array(
'contain' => array(
'Event' => array(
'EventVenue' => array(
'Country'
)
)
)
)
Try this:
$item = $this->Event->findBySlug($slug,array(
'contain' => array(
'EventVenue' => array(
'Country'
)
)
);
Update
Turns out findBy does not support Containable. You could use this to get the desired result:
$item = $this->Event->find('first',array(
'conditions' => array(
'Event.slug' => $slug
),
'contain' => array(
'EventVenue' => array(
'Country'
)
)
);
Oh and make sure you have this in the model: public $actsAs = array('Containable');
try this method:
$this->Event->recusive = 2;
$item = $this->Event->findBySlug($slug);
You need to set the recursive to 2 before you make the find, something like this
$this->Event->recursive = 2;
with this, you'll get the Event, the EventVenue and the Country on one shot
Hope it helps
I'm trying to use on the fly associations to trim down the data I retrieve, but the model I'm using is associated to other models with a re-named field because I have 2 of the same models associated with it.
So, here's the model, say 'test', that has two 'user' fields, both related to the User model.
In the model:
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'User_Watched' => array(
'className' => 'User',
'foreignKey' => 'user_id_watched'
)
);
When I retrieve data related to 'test', I want to only retrieve particular data linked to the 'User' and 'User_Watched' fields without any other nested information.
But when I do:
$this->User->unbindModel(array('hasMany' => array('something1', 'something2')), false);
then something1 and something2 data does not show up for the 'User' field of model 'test', but is still retrieved for the 'User_watched' field.
Can I not retrieve unwanted data for the 'User_watched' field?
Hope this makes sense... :)
KcYxA,
Containable behavior might help a lot in this case, as benjamin mentioned, your "find" queries would look like:
$this->User->find('first', array(
'conditions' => array('User.id' => $id),
'contain' => array('UserWatched')
));
In this case, you won't have to use unbindModel method. In this example, you'll get User and UserWatched data.
If you need only User data from "find", then tell Cake to "$this->User->contain();" so it won't go further then User model.
to use on the fly associations to trim
down the data I retrieve
Good idea.
'foreignKey' => 'user_id_watched'
should possibly be:
'foreignKey' => 'user_watched_id'.
Edit 1: At least this would make sense according to my current understanding. If user_id is a correct foreign key(FK), which cakephp uses to unbind the relations, but user_id_watched isn't, than your described behavior is explained.
Edit 2: The Containable behavior gives you another tool for controlling associated models.
Change $primaryKey in fly, run controller
Sample:
// Models
//....
class PreProductoDescripcion extends AppModel {
/**
* Primary key field
*
* #var string
*/
public $primaryKey = 'id_producto_descripcion';
//....
//....
}
class SenasaPedidosDetalles extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'cod_tango';
public $belongsTo = array(
'SenasaPedidos' => array(
'className' => 'SenasaPedidos',
'foreignKey' => 'senasa_pedidos_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'PreProductoDescripcion' => array(
'className' => 'PreProductoDescripcion',
'foreignKey' => 'cod_tango',
//'conditions' => array('SenasaPedidosDetalles.cod_tango' => 'PreProductoDescripcion.codigo'),
'fields' => '',
'order' => ''
)
);
//....
#
// Controller Fly
//...
$this->SenasaPedidos->Behaviors->load('Containable');
$this->SenasaPedidos->SenasaPedidosDetalles->PreProductoDescripcion->primaryKey = 'codigo';
$datos = $this->SenasaPedidos->find(
'first', array(
'fields' => array( 'SenasaPedidos.*' ),
'conditions' => array( 'SenasaPedidos.id' => $id ),
'contain' => array(
'Usuarios' => array(
'fields' => array( 'Usuarios.apellido_nombre' )
),
'Clientes' => array(
'fields' => array( 'Clientes.razon_social' )
),
'Provincias' => array(
'fields' => array( 'Provincias.nombre' )
),
'Transportes' => array(
'fields' => array( 'Transportes.razon_social' )
),
'SenasaPedidosDetalles' => array(
'fields' => array( 'SenasaPedidosDetalles.*' ),
'PreProductoDescripcion' => array(
'fields' => array(
'PreProductoDescripcion.id_producto_descripcion',
'PreProductoDescripcion.descripcion'
)
)
),
)
));
//...