CakePHP: How to set variables with multiple level dependancies - php

In my controller I want to set a variable(A) which has a one to many relationship with another model(B) which has a HABTM (has and belongs to many) relationship with ANOTHER model(C).
Currently when I set the variable in the controller I can access the model(B) in the view, but not ITS dependancies (model C):
//A's controller...
public function admin_view($id = NULL) {
$A = $this->A->findById($id);
$this->set('A', $A);
}
Here's what I see if I dump the variable in the view:
//A's admin_view.ctp...
//debug($A);
array(
'A' => array(
'id' => '1',
'name' => 'Name',
'created' => '2013-04-04 15:25:54',
'modified' => '2013-04-04 15:25:54'
),
'B' => array(
(int) 0 => array(
'id' => '1',
'created' => '0000-00-00 00:00:00',
'modified' => '2013-04-05 10:31:42'
),
(int) 1 => array(
'id' => '13',
'created' => '0000-00-00 00:00:00',
'modified' => '2013-04-05 10:31:42'
Is there a way to set the variable such the each "B" will have it's respective Cs included?

http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
// In your model
var $actsAs = array('Containable');
// In your controller
public function admin_view($id = NULL) {
$this->A->contain(array('B' => array('C')));
$A = $this->A->findById($id);
$this->set('A', $A);
}
That should give you what you need, setting recursive to 2 is the easy way out, but you'll get redundant data if you have other associations.

Well then, explaining $recursive and Containable behavior:
Recursive is a value between -1 to 2, and basically it tells the model "I want to fetch this record AND all records associated with it" if it's set to 2. If it's -1, then with find or read you only get that model data.
Containable let's you specify which models/fields-of-other-models you want to fetch (they have to have an association, though).
I've repeated many times I'm not a fan of $recursive != -1 because I feel it doesn't let you control what data you retrieve and when to do it. I recommend you use
class AppModel extends Model {
public $actsAs = array('Containable');
public $recursive = -1;
//etc
}
in the AppMdel so everything isn't recursive and containable by default (it isn't necessary for the query to work, though). Then, regarding your question, the find query should be like
$A = $this->A->find('first', array('conditions'=>array('id'=>$id),
'contain'=>array('B-model'=>array('C-model'))));

Related

Why only last item is saved in database?

I have problem, becouse only last item from loop is saved in database.
Im using CakePhp 2.x
Controller:
for ($x=1; $x <= count($this->request->data['Goodsandoffer'])/3;$x++){
$promID = $this->request->data['Goodsandoffer']['promotionaloffer_id_'.$x];
if($this->request->data['Goodsandoffer']['cenaPromocyjna_'.$x] != ''){
$helperReqestTable3 = array('promotionaloffer_id'=>$this->request->data['Goodsandoffer']['promotionaloffer_id_'.$x],'good_id'=>$this->request->data['Goodsandoffer']['good_id_'.$x],'cenaPromocyjna'=>$this->request->data['Goodsandoffer']['cenaPromocyjna_'.$x]);
$helperReqestTable['Goodsandoffer']=$helperReqestTable3;
debug($helperReqestTable);
$this->Goodsandoffer->save($helperReqestTable);
}
}
Here is how look my debug in loop:
array(
'Goodsandoffer' => array(
'promotionaloffer_id' => '7',
'good_id' => '18',
'cenaPromocyjna' => '1'
)
)
And in next interation:
array(
'Goodsandoffer' => array(
'promotionaloffer_id' => '7',
'good_id' => '19',
'cenaPromocyjna' => '2'
)
)
In database is created only one row with last item.
Model:
class Goodsandoffer extends AppModel {
public $displayField = 'id';
public $belongsTo = array(
'Promotionaloffer' => array(
'className' => 'Promotionaloffer',
'foreignKey' => 'promotionaloffer_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Good' => array(
'className' => 'Good',
'foreignKey' => 'good_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
Have you tried calling $this->Goodsandoffer->create() before you call save? That way you're definitely telling Cake to create a new record each time.
The general process of creating and saving data in Cake is:
$this->Model->create()
$this->Model->set($data_array)
$this->Model->save()
You can also eliminate step 2 above by passing you $data_array to the save() function:
$this->Model->create();
$this->Model->save($data_array);
NOTE: from the manual (if you aren't using create()):
When calling save in a loop, don’t forget to call clear().
Another way you could create new data would be to make sure the primary key for your model is null in the data set you pass into save, although this is a little less obvious and probably best to stick to the create/[set/]save flow:
$data = array('id' => null, 'somefield' => 'foobar');
$this->Model->save($data); // new record created
In cakephp 2.0 $this->Model->create() create work fine. But if you are using cakephp version 3 or greater then 3. Then follow the below code
$saveData['itemId'] = 1;
$saveData['qty'] = 2;
$saveData['type'] = '0';
$saveData['status'] = 'active';
$saveData = $this->Model->newEntity($saveData);
$this->Model->save($materialmismatch);
In normal case we use patchEntity
$this->Model->patchEntity($saveData, $this->request->data);
It will only save last values of array so you have to use newEntity() with data

$this->params returns null in cakephp model

I decided to add some extra data about the controllers and actions in some model beforeSave as follows:
//in the model
public function beforeSave() {
$this->data[$this->alias]['path'] = 'blah blan';
debug($this->params);
die(); //for debugging!
}
The printout of debug returns null! The model I uses is the Comment model of the comments plugin. I need to access params to get the current controller, actions and some url parameters.
Indeed, I plan to change the way that comments plugin lists the comments from model based to be path based to solve the issue of need comments for more than one action depend on the same model.
Finally I found the solution: It is in Router object method getParams();
//in the model
public function beforeSave() {
$this->data[$this->alias]['path'] = 'blah blan';
debug(Router::getParams());
die(); //for debugging!
}
it prints out something like:
array(
'plugin' => null,
'controller' => 'qurans',
'action' => 'view',
'named' => array(
'comment' => '0'
),
'pass' => array(
(int) 0 => '8'
)
)

has_many through using custom table and field names

I'm using php.activerecord, and I am trying to link tables together. I'm not using their structure, but php.activerecord assumes I am, so it doesn't always work. I'm trying to use it on an already made app, so I can't change the database.
I learned from my previous question - Model association with custom table and key names - that I need to be as explicit as possible with the primary_key and foreign_key fields.
I'm having issues now using has_many through. I keep getting NULL, and I have no idea why.
So, here's a scenario: I have 3 tables, contacts, contactPrefs, and preferences. Those tables are as follows
contacts
--------
contactID
name
status
contactPrefs
------------
contactID
prefID
prefValue
preferences
-----------
prefID
name
description
Each contact has multiple contactPrefs. Each contactPrefs has one preferences. I tried to use has_many to get this working, but it's not. Here are my models:
Contacts.php:
<?php
class Contact extends ActiveRecord\Model {
static $primary_key = 'contactID';
static $has_many = array(
array(
'prefs',
'foreign_key' => 'contactid',
'primary_key' => 'contactid',
'class_name' => 'ContactPref'
),
array(
'preferences',
'foreign_key' => 'prefid',
'primary_key' => 'prefid',
'through' => 'prefs',
'class_name' => 'Preference'
)
);
}
ContactPref.php:
<?php
class ContactPref extends ActiveRecord\Model {
static $table_name = 'contactPrefs';
static $belongs_to = array(
array(
'contact',
'foreign_key' => 'contactid',
'primary_key' => 'contactid'
),
array(
'preference',
'foreign_key' => 'prefid',
'primary_key' => 'prefid'
)
);
}
Preference.php:
<?php
class Preference extends ActiveRecord\Model {
static $primary_key = 'prefID';
static $has_many = array(
array(
'prefs',
'foreign_key' => 'prefid',
'primary_key' => 'prefid',
'class_name' => 'ContactPref'
)
);
}
According to the docs, I now should be able to the following:
<?php
var_dump(Contact::find(1234)->preference);
I cannot. I get NULL. Oddly, I can do this:
<?php
var_dump(Contact::find(1234)->prefs[0]->preference);
That works correctly. But, shouldn't I be able to access the preference object directly through the contact object? Am I misunderstanding the docs (they aren't the greatest, in my opinion)? Am I doing something wrong?
First you are reading the docs with a small flaw. In the docs you are shown:
$order = Order::first();
# direct access to users
print_r($order->users); # will print an array of User object
Which you are already doing via Contact::find(1234)->prefs. Let me boil it down a bit
$contact = Contact::find(1234);
# direct access to prefs
print_r($contact->prefs); # will print an array of ContactPref object
Second, what you actually want is undefined. What should Contact::find(1234)->preference actually do? Return the preference of the first ContactPref? Return an array of Preference objects?
I feel like offering both:
<?php
class Contact extends ActiveRecord\Model {
static $primary_key = 'contactID';
static $has_many = array(
array(
'prefs',
'foreign_key' => 'contactid',
'primary_key' => 'contactid',
'class_name' => 'ContactPref'
),
array(
'preferences',
'foreign_key' => 'prefid',
'primary_key' => 'prefid',
'through' => 'prefs',
'class_name' => 'Preference'
)
);
public function get_preference() {
return isset($this->prefs[0])
? $this->prefs[0]->preference
: null
;
}
public function get_preferences() {
$preference=array();
foreach($this->prefs as $pref) {
$preference[]=$pref;
}
return $preference;
}
}
Let me explain a little bit what I have done. The ActiveRecord\Model class has a __get($name) function that looks for another function called get_$name, where $name in your case is preference (for the first result) and preference (for the entire collection). This means you can do Contact::find(1234)->preference which would be the same as doing Contact::find(1234)->prefs[0]->preference (but safer, due to the check) and Contact::find(1234)->preferences to get the entire collection of preferences.
This can be made better or optimized in numerous ways, so please don't take it as it is, but do try and adapt it to your specific situation.
For example you can either use the id of the preference as an index in the array or either not force a load of more data from ContactPrefs than the ones you are going to use and try a more intricate query to get the preference objects that you specifically need.
If I find a better implementation by getting through to work in the relationship definition, I'll return. But seeing the Unit Tests for active record, I'm skeptical.
There are several things that look strange, so it's not easy to come to a "this will fix it" for you, but this is an issue at least:
Fieldnames should always be lower-case in phpactiverecord. SQL doesn't mind it either way (not that table names ARE case-sensitive, but column names aren't). So make this:
static $primary_key = 'contactID';
into
static $primary_key = 'contactid';
The connections // find commands can be used in SQL, in which case it doesn't really matter how your key-string is 'cased', so some stuff works. But if the connection goes trough the inner-workings of phpmyadmin, it will fail. So check out this contactID but also the prefID.
Again, this goes only for COLUMN names, so don't go changing classnames or table-names to lowercase.
(extra point: phpmyadmin has trouble with combined primary keys. So while it might be ugly, you could add an extra row to your contactprefs table (if you don't allready have it) called id, to make that table actually have something to work with. It wouldn't give you much trouble, and it would help the activerecord library a lot)
Try the following:
<?php
var_dump(Contact::find(1234)->preferences);
The documentation says that with a has_many relationship, it should be referenced by a plural (http://www.phpactiverecord.org/projects/main/wiki/Associations#has_many_through). The Contact::find(1234) returns a Contact object which has multiple contactPrefs with their each Preference. In addition, in your Contact model, you specify the has_many as preferences .
static $has_many = array(
array(
'prefs',
'foreign_key' => 'contactid',
'primary_key' => 'contactid',
'class_name' => 'ContactPref'
),
array(
'preferences',
'foreign_key' => 'prefid',
'primary_key' => 'prefid',
'through' => 'prefs',
'class_name' => 'Preference'
)
);
Edit Through Modification:
Try the following Contact model
<?php
class Contact extends ActiveRecord\Model {
static $primary_key = 'contactID';
static $has_many = array(
array(
'prefs',
'foreign_key' => 'contactid',
'class_name' => 'ContactPref'
),
array('preferences',
'through' => 'prefs',
'class_name' => 'Preference',
'primary_key' => 'prefID')
);
}

CakePHP how to retrieve HABTM data with conditions?

I use CakePHP 2.2.2
I have 3 tables: restaurants, kitchens and kitchens_restaurants - join table for HABTM.
In Restaurant model I have:
public $hasAndBelongsToMany = array(
'Kitchen' =>
array(
'className' => 'Kitchen',
'joinTable' => 'kitchens_restaurants',
'foreignKey' => 'restaurant_id',
'associationForeignKey' => 'kitchen_id',
'unique' => true,
'conditions' => '',
'fields' => 'kitchen',
'order' => '',
'limit' => '',
'offset' => '',
),
The problem is that I have separate controller for my main page in which I need to retrieve data from this models with complex conditions.
I added
public $uses = array('Restaurant');
to my main page controller and here comes the part where I need your advices.
I need to select only those restaurants where kitchen = $id.
I've tried to add
public function index() {
$this->set('rests', $this->Restaurant->find('all', array(
'conditions' => array('Restaurant.active' => "1", 'Kitchen.id' => "1")
)));
}
and I got SQLSTATE[42S22]: Column not found: 1054 Unknown column in 'where clause' error.
Obviously I need to fetch data from "HABTM join table" but I don't know how.
TLDR:
To retrieve data that's limited based on conditions against a [ HABTM ]'s association, you need to use [ Joins ].
Explanation:
The code below follows the [ Fat Model/Skinny Controller ] mantra, so the logic is mostly all in the model, and just gets called from a controller.
Note: You don't need all those HABTM parameters if you follow the [ CakePHP conventions ] (which it appears you are).
The below code has not been tested (I wrote it on this site), but it should be pretty darn close and at least get you in the right direction.
Code:
//Restaurant model
public $hasAndBelongsToMany = array('Kitchen');
/**
* Returns an array of restaurants based on a kitchen id
* #param string $kitchenId - the id of a kitchen
* #return array of restaurants
*/
public function getRestaurantsByKitchenId($kitchenId = null) {
if(empty($kitchenId)) return false;
$restaurants = $this->find('all', array(
'joins' => array(
array('table' => 'kitchens_restaurants',
'alias' => 'KitchensRestaurant',
'type' => 'INNER',
'conditions' => array(
'KitchensRestaurant.kitchen_id' => $kitchenId,
'KitchensRestaurant.restaurant_id = Restaurant.id'
)
)
),
'group' => 'Restaurant.id'
));
return $restaurants;
}
//Any Controller
public function whateverAction($kitchenId) {
$this->loadModel('Restaurant'); //don't need this line if in RestaurantsController
$restaurants = $this->Restaurant->getRestaurantsByKitchenId($kitchenId);
$this->set('restaurants', $restaurants);
}
There is a much cleaner way than the solution provided by Dave.
First you need to set a reverse HABTM Relationship between Restaurant and Kitchen in the Kitchen Model.
Than you just make a find for the Kitchen you are interested in (id = 1) and you will get the associated restaurants, using Containable Behavior for filtering by Restaurant fields.
$this->Restaurant->Kitchen->Behaviors->attach('containable'); // Enable Containable for Kitchen Model
$this->Restaurant->Kitchen->find('first', array(
'recursive' => -1 // don't collect other data associated to Kitchen for performance purpose
'conditions' => array('Kitchen.id' => 1),
'contain' => array('Restaurant.active = 1')
));
Source
You can not need use [join], because use have setting [ HABTM ]'s association
Kitchen model hasAndBelongsToMany Restaurant model so that you can code as bellow
KitchensControllers
<?php
public function index() {
$this->Kitchen->recursive = 0;
$kitchens = $this->Kitchen->find('all', array('contain' => array('Restaurant')));
$this->set('kitchens', $kitchens);
}
?>
Good luck!

Yii relation failing with indexes > 5

I have a very simple relation defined as follows (aId and bId are the primary keys for each table).
class A extends CActiveRecord
{
// #var int32 $aId
}
class B extends CActiveRecord
{
// #var int32 $bId
// #var int32 $aId
public function relations()
{
return array(
'a'=>array(self::HAS_ONE, 'A', 'aId'),
);
}
}
As long as bId <= 5, I can access A through $bModel->a without any problems. What's strange is for bId > 5, $bModel->a is null. I've checked $bModel->aId for bId > 5 and the foreign key is correct. I can even access A with $aModel = A::model()->findByPk($bModel->aId);. I can also manually edit my bIds in the database table, which produces the same result.
I have no idea what's causing the relation to fail for primary key's greater than five. Any suggestions for troubleshooting? I'm at a loss.
EDITED
It turns out I wasn't using the relation properly. I should have used BELONGS_TO.
class B extends CActiveRecord
{
// #var int32 $bId
// #var int32 $aId
public function relations()
{
return array(
'a'=>array(self::HAS_ONE, 'A', 'aId'),
);
}
}
HAS_ONE was causing B to use bId to index A. Since I had five instances of A in my database that worked for bID < 5
Enable query logging in your application config to see what exactly is happening.
Do you get any results when manually running those queries?
'components' => array(
'db' => array(
(..)
'enableParamLogging' => true,
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
// Show log messages on web pages
array(
'class' => 'CWebLogRoute',
'categories' => 'system.db.CDbCommand', //queries
'levels' => 'error, warning, trace, info',
//'showInFireBug' => true,
),
(I'd post this as a comment rather than an answer, but it seems I can't)
I recommend you to use this -> Yii Debug Toolbar (it is created by my friend here in Ukraine).
Can you provide mysql structure + some example data. Thanks.

Categories