I'm trying to have this query
SELECT * FROM `rentprograms` AS `Rentprogram`
inner join `vehiclerentprograms` as `Vehiclerentprogram` on `Vehiclerentprogram`.`rentprogramid` = `Rentprogram`.`id`
inner join `vehicles` AS `Vehicle` ON `Vehicle`.`id` =`Vehiclerentprogram`.`vehicleid` WHERE `Vehicle`.`id` = 1
Code in CakePHP
$this->Rentprogram->find('all'), array(
'fields'=>array('*'),
'joins' => array(
array(
'table' => 'vehiclerentprograms',
'alias' => 'Vehiclerentprogram',
'type'=>'inner',
'conditions' => array(
'Vehiclerentprogram.rentprogramid' => 'Rentprogram.id',
)
),
array(
'table' => 'vehicles',
'alias' => 'Vehicle',
'type'=>'inner',
'conditions' => array(
'Vehicle.id' => 'Vehiclerentprogram.vehicleid',
)
)
),
);
But it only display the value of Rentprogram. How can i have all the fields related to Rentprogram, Vehicle, Vehiclerentprogram.
There's no value in using an MVC framework and do the dirty joins by hand. You'd better use Cake conventions, which lets you access Cake's libraries and tools which in turn speed up the development process quite a lot. In this case you have to setup models and associations between models (I hope you have heard of has-many, belongs-to, many-to-many and so on).
CakePHP ships with an invaluable DAO layer and a code generator called bake. Once you design the database schema, forget about SQL and think in terms of your business objects. First, create three tables in MySQL (I used a minimal set of fields and deduced the structure from your query):
CREATE TABLE `programs` (
`id` int(11) AUTO_INCREMENT,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `vehicles` (
`id` int(11) AUTO_INCREMENT,
`model` varchar(128) DEFAULT NULL,
`plate` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `vehicle_programs` (
`id` int(11) AUTO_INCREMENT,
`program_id` int(11) DEFAULT NULL,
`vehicle_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
Then run the shell script:
Console/cake bake all
and select one table at a time (remember vehicle_programs must be the last one). This will generate all Models, Controllers and Views files for you. Then you can start filling your database with test data. Point your browser to http://host/vehicle_programs and put some vehicle and program in.
Finally I will show you how to retrieve all of the fields in one query. Suppose that you want to show everything when listing vehicle_programs. In the index() method of VehicleProgramsController you have to set $this->VehicleProgram->recursive to 1, so that it fetches related models fields as well. In the view index.ctp you'll now be able to access fields like
<?php
foreach ($vehiclePrograms as $vehicleProgram) {
echo $vehicleProgram['Program']['start'];
echo $vehicleProgram['VehicleProgram']['id'];
echo $vehicleProgram['Vehicle']['plate'];
}
Note if we hadn't set Model->recursive to 1, Cake wouldn't have fetched fields of related models (Vehicle and Program) for us.
Incidentally, I think not setting the fields key at all should do the trick, since Cake reads everything by default. However, the correct solution is using relationships between model classes - when you run bake it puts the following in Model/Vehicle.php:
class Vehicle extends AppModel {
public $hasMany = array(
'VehicleProgram' => array(
'className' => 'VehicleProgram',
'foreignKey' => 'vehicle_id',
'dependent' => false
)
);
}
and symmetric associations in Model/VehicleProgram.php
You can use this method
$this->Rentprogram->find('all'), array(
'fields' => array('Rentprogram.*', 'Vehicle.*', 'Vehiclerentprogram.*'), ...
Related
I would like to know how to retrieve translation inside a query with cakephp 3.3.
I have already added inside Table:
$this->addBehavior('Translate', ['fields' => ['textContent']]);
This is my query:
$query = $objTable->find('all')
->where(['admin_template_id' => $id])
->contain(['AdminObjects']);
I have already tried this:
$query = $objTable->find('all')
->where(['admin_template_id' => $id])
->contain(['AdminObjects', 'translations']);
But returns me error 500.
My translation table is the same of the cakephp documentation:
CREATE TABLE i18n (
id int NOT NULL auto_increment,
locale varchar(6) NOT NULL,
model varchar(255) NOT NULL,
foreign_key int(10) NOT NULL,
field varchar(255) NOT NULL,
content text,
PRIMARY KEY (id),
UNIQUE INDEX I18N_LOCALE_FIELD(locale, model, foreign_key, field),
INDEX I18N_FIELD(model, foreign_key, field)
);
How can I fin translation inside a find all query?
Thanks
You may use find method 'translations' instate of 'all'.
try
$query = $objTable->find('translations')
->where(['admin_template_id' => $id])
->contain(['AdminObjects']);
instate of
$query = $objTable->find('all')
->where(['admin_template_id' => $id])
->contain(['AdminObjects']);
officeial Doc Retrieve All Translations
Let's say I have two tables:
CREATE TABLE drinks (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
morning_drink_id INT,
evening_drink_id INT
);
How can I make those drink_id references valid?
I’ve tried:
adding a view
CREATE VIEW morning_drinks AS SELECT * FROM drinks;
CREATE VIEW evening_drinks AS SELECT * FROM drinks;
adding foreign keys
FOREIGN KEY morning_drink_key (morning_drink_id) REFERENCES drinks(id),
FOREIGN KEY evening_drink_key (evening_drink_id) REFERENCES drinks(id)
bake craches in both cases... Is there a proper way?
public $belongsTo = array(
'Drink' => array(
'className' => 'Drink',
'foreignKey' => 'morning_drink_id'
)
);
this you can add to Users model. And this is how to do it.
edit:
Bake is expecting tables for your two foreign keys, and it’s complaining about them. I got the same error as you when I deleted the ‘morning_drinks’ view, else it created all. Add those two views and try again.
I've got a Cakephp Project with an 'Addresses' table with the following structure:
CREATE TABLE `addresses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`company` varchar(50) NOT NULL,
`address1` varchar(50) NOT NULL,
`address2` varchar(50) DEFAULT NULL,
`city` varchar(40) NOT NULL,
`state` varchar(2) NOT NULL,
`country` varchar(2) NOT NULL,
`zip` varchar(5) NOT NULL,
PRIMARY KEY (`id`)
)
There is a page in this project which asks the user for both a Shipping Address and a Billing Address, and im not certain how to structure the names of the form inputs to allow multiple instances of the same database fields on one page
In the View, I've attempted to use an alias to seperate the two instances of the Address fields
I.E.-
<?=$this->Form->input('Shipaddress.zip', array('label' => 'Zip Code'));?>
...
<?=$this->Form->input('Billaddress.zip', array('label' => 'Zip Code'));?>
then in the view, i tried to seperate the two instances, validate both, and set the appropriate $this->validationError values to properly display the errors to the correct field views
// place in arrays with proper model name ['Address']
$ship_array['Address'] = $this->request->data['Shipaddress'];
$bill_array['Address'] = $this->request->data['Billaddress'];
//Set Data to model, Validate Against model, change model name in validationErrors to match aliased fields, and remove validationErrors for ['Address']
$this->Address->set($ship_array);
$shipping_valid = $this->Address->validates(array('fieldList' => array('name', 'company', 'address1', 'address2', 'city', 'state', 'country', 'zip')));
$this->validationErrors['Shipaddress'] = $this->validationErrors['Address'];
$this->validationErrors['Address'] = array();
//Do it again for Billing Address fields
$this->Address->set($bill_array);
$billing_valid = $this->Address->validates(array('fieldList' => array('name', 'company', 'address1', 'address2', 'city', 'state', 'country', 'zip')));
$this->validationErrors['Billaddress'] = $this->validationErrors['Address'];
$this->validationErrors['Address'] = array();
unfortunately, this doesnt appear to work, and i'm afraid that I've gone too far trying to make this work...
can someone give my a kick in the right direction on how this can be done properly?
Figured out how to do it on my own...
in /app/Model i created 'ShippingAddress.php' and 'BillingAddress.php', Both Extend "Address"
//ShippingAddress.php
<?php
App::uses('Address', 'Model');
class ShippingAddress extends Address {
}
//BillingAddress.php
<?php
App::uses('Address', 'Model');
class BillingAddress extends Address {
}
To prevent the new models from using tables named after them, we edit the parent Address.php and set $useTable so that both extended models use Addresses Table
//Address.php
...
public $useTable = 'addresses';
...
then its just a matter of inserting the two instances of the input fields into the view... no renaming models, no modifying validationErrors, it just works :)
Page table
(1)
|
|
(*)
User_Moderate_Page (*)----------- (1)Access_level table
(*)
|
|
(1)
User table
How do i Model such a ternary relationship in CakePhp?
User to Page can be modelled using the hasBelongtoMany Relationship. But User_Moderate_page is just an association table, should I even write a Model for User_Moderate_Page in Cake?
I'm not sure CakePHP accepts this, but what you should do is create the table with a primary key and the 3 foreign keys. Somewhat like this:
CREATE TABLE IF NOT EXISTS `mydb`.`access_levels_pages_users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`page_id` INT NOT NULL ,
`access_level_id` INT NOT NULL ,
`user_id` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_access_levels_pages_users_pages` (`page_id` ASC) ,
INDEX `fk_access_levels_pages_users_access_levels1` (`access_level_id` ASC) ,
INDEX `fk_access_levels_pages_users_users1` (`user_id` ASC) ,
CONSTRAINT `fk_access_levels_pages_users_pages`
FOREIGN KEY (`page_id` )
REFERENCES `mydb`.`pages` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_access_levels_pages_users_access_levels1`
FOREIGN KEY (`access_level_id` )
REFERENCES `mydb`.`access_levels` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_access_levels_pages_users_users1`
FOREIGN KEY (`user_id` )
REFERENCES `mydb`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
Now, I'm not sure Cake will bake this table, so you might have to try and make the models by hand, this table would have belongsTo the 3 other tables. The other 3 tables non association tables will have to have a HMABTM relationship with the other 2, as in users HMABTM access_levels and pages and so on.
Again, not sure if it will work. I would suggest maybe trying to see if you can model it in a different manner.
Let me generalize it by describing it with generic tables:
Lets say you have 3 tables - firsts, seconds, thirds - each with primary keys 'id'.
let your join table be called 'firsts_seconds_thirds' with foreign keys to each main table:
first_id
second_id
third_id
<additional fields of this association table>
usually we define HABTM relationships between tables, in this case we need to create a cake model for the join table - lets call it FirstsSecondsThird (By cakePhp's naming conventions)
The relationship between models you need to define is:
First hasMany FirstsSecondsThird
Second hasMany FirstsSecondsThird
Third hasMany FirstsSecondsThird
FirstsSecondsThird belongsTo First,Second,Third
The need for this is explained here - Associations: Linking Models Together
Code for the same:
class First extends AppModel {
public $hasMany = array(
'FirstsSecondsThird' => array(
'className' => 'FirstsSecondsThird',
'foreignKey' => 'first_id'
)
);
}
//Same for classes 'Second' and 'Third'
class FirstsSecondsThird extends AppModel {
public $belongsTo = array(
'First' => array(
'className' => 'First',
'foreignKey' => 'first_id'
),
'Second' => array(
'className' => 'Second',
'foreignKey' => 'second_id'
),
'Third' => array(
'className' => 'Third',
'foreignKey' => 'third_id'
)
);
}
The models are perfectly setup, but now inserting/updating/deleting from the main/join table should be done correctly or they are of no use.
Model::saveMany() and Model::saveAssociated(), using the option 'deep' etc. need to be used. Read about it here. You also need to think about ON DELETE RESTRICT/CASCADE for these join tables and model them appropriately.
Look up ACL. It is complicated, but it is what you need (especially if you need the flexibility in setting up who can moderate what page)
Hi i am new in cake php and can't solve the problem. The problem is I have a table like;
id varchar(16)
parent_id varchar(16)
text text
user_id bigint(20)
is_deleted_by_user bit(1)
is_deleted_by_us bit(1)
who_deleted bigint(20)
who_answered bigint(20)
modified_at datetime
created_at datetime
in this table i want to give relations between users table and user_id, who_deleted, who_answered. I mean user_id, who_deleted and who_answered are one user id. How can i give relations between users table and this table?
It's relatively easy to create multiple relationships to the same model. There's a section of the documentation dedicated to it. Here's how I've done it for a Resource model that has multiple fields associated with a Binary model:
class Resource extends AppModel {
public $belongsTo = array (
'PDF' => array (
'className' => 'Binary',
'foreignKey' => 'pdf_file_id'
),
'MSWord' => array (
'className' => 'Binary',
'foreignKey' => 'msword_file_id'
)
);
... other class code ...
}
The resources table contains pdf_file_id and msword_file_id fields which each reference a Binary record.
Hope that helps.