join multiple tables in CakePHP and retrive data [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Updated Question
I am trying to Join Multiple tables in CakePHP and retrieve their data.
I have created my Model but not getting relevant result.
Below is my Table Structure.
Fields needed :
Equipment Name
Equipment Description
Equipment Type name according to Equipment id
Equipment Type Sizes names according to Type id
Sizes Stock.
Model:Equipment.php
class Equipment extends AppModel {
public $useTable = 'equipments';
var $name = 'Equipment';
public $cacheQueries = false;
public $hasMany = array(
'Sizes' => array(
'className' => 'EquipmentSize',
'foreignKey' => 'equipment_id'
)
);
}
Model:EquipmentSizes .php
class EquipmentSizes extends AppModel {
public $useTable = 'equipment_sizes';
var $name = 'EquipmentSizes';
public $cacheQueries = false;
public $belongsTo = array(
'Equipment' => array(
'className' => 'Equipment',
'foreignKey' => 'equipment_id',
'fields' => array('id', 'sizes')
)
);
}
Model:EquipmentType.php
class EquipmentType extends AppModel {
public $useTable = 'equipment_types';
var $name = 'EquipmentType';
public $cacheQueries = false;
public $hasMany = array(
'Sizes' => array(
'className' => 'EquipmentTypesSize',
'foreignKey' => 'equipment_type_id'
)
);
}
Model:EquipmentTypesSizes.php
class EquipmentTypesSizes extends AppModel {
public $useTable = 'equipment_types_sizes';
var $name = 'EquipmentTypesSizes';
public $cacheQueries = false;
public $belongsTo = array(
'EquipmentType' => array(
'className' => 'EquipmentType',
'foreignKey' => 'equipment_type_id',
'fields' => array('id', 'sizes')
)
);
}

You have forgotten the foreign keys on some of your models (Equipment.php, EquipmentType.php) that have hasToMany relationship. Correct your models first then try to query an equipment and you can see there the associated models of Equipment. You can then base your conditions to that.
Updated - Equipment.php
class Equipment extends AppModel {
public $useTable = 'equipments';
var $name = 'Equipment';
public $cacheQueries = false;
public $hasMany = array(
'Sizes' => array(
'className' => 'EquipmentSize',
'foreignKey' => 'equipment_id'
),
'EquipmentType' => array(
'className' => 'EquipmentType',
'foreignKey' => 'equipment_id'
)
);
}
EquipmentSizes.php is correct.
Updated - EquipmentType.php
class EquipmentType extends AppModel {
public $useTable = 'equipment_types';
var $name = 'EquipmentType';
public $cacheQueries = false;
public $hasMany = array(
'Sizes' => array(
'className' => 'EquipmentTypesSize',
'foreignKey' => 'equipment_type_id'
)
);
public $belongsTo = array(
'Equipment' => array(
'className' => 'Equipment',
'foreignKey' => 'equipment_id'
)
);
}
EquipmentTypesSizes.php is correct.

Related

not save data to 2 table have foreigenkey oncakephp

On project cakephp. I have 2 model
<?php class VisaPerson extends AppModel {
public $name = 'VisaPerson';
public $primaryKey = 'id';}?>
and
<?php class VisaProcess extends AppModel {
public $name = 'VisaProcess';
public $primaryKey = 'id';
public $belongsTo = array(
'VisaPerson' => array (
'className' => 'VisaPerson',
'foreignKey' => 'people_id'
)
);
}
?>
In controller, I writed:
if ($this->request->is('post')) {
if (!empty($this->request->data)) {
$person = $this->VisaPerson->save($this->request->data);
if (!empty($person)) {
$this->request->data['VisaProcess']['people_id'] = $this->$person->id;
$this->VisaPerson->VisaProcess->save($this->request->data);
}
}
Data saved on VisaPerson but on VisaProcess people_id not auto save.
Plese help me!
As I remember you need to add this into yours VisaPerson model:
public $hasMany = array(
'VisaProcess' => array(
'className' => 'VisaProcess',
'foreignKey' => 'people_id'
)
);
After that you only need to save VisaPerson and both tables will be filled (if $this->request->data['VisaProcess'] and $this->request->data['VisaPerson'] exists):
$this->VisaPerson->save($this->request->data);

CakePHP Multidimensional Model

I'm having some trouble with CakePHP's models.
I have three tables - CC_PLAYLIST, CC_PLAYLISTCONTENTS, and CC_FILES.
I'd like to get a list of all playlists, with all of their contents, and then the relevant file information for each piece of playlist content.
I.E
Playlist 1
-- Playlist Content 1
---- File Info
-- Playlist Content 2
---- File Info
-- Playlist Content 3
---- File Info
Playlist 2
-- Playlist Content 123
---- File Info
In my controller I have:
$playlistcontent = $this->AirtimePlaylist->find('all') however that seems to turn up a flat array with all playlistcontents, all files, and empty playlist arrays.
AirtimeFile.php
class AirtimeFile extends AppModel {
public $useTable = 'cc_files';
public $actsAs = array('Containable');
public $hasMany = array('AirtimeFileAttribute' => array(
'className' => 'AirtimeFileAttribute',
'foreignKey' => 'track_id'
));
}
AirtimePlaylist.php
class AirtimePlaylist extends AppModel {
public $useTable = 'cc_playlist';
public $actsAs = array('Containable');
public $hasMany = array('AirtimePlaylistContent' => array(
'className' => 'AirtimePlaylistContent',
'foreignKey' => 'playlist_id'
));
}
AirtimePlaylistContent.php
class AirtimePlaylistContent extends AppModel {
public $useTable = 'cc_playlistcontents';
public $actsAs = array('Containable');
public $hasOne = array('AirtimePlaylist' => array(
'className' => 'AirtimePlaylist',
'foreignKey' => 'id'
),'AirtimeFile' => array(
'className' => 'AirtimeFile',
'foreignKey' => 'id'
));
}
In your controller you need to use contain
$model = $this->AirtimePlaylist->find('all',
array(
'contain' => array('AirtimePlaylistContent' => array('AirtimeFile') )
)
);

CakePHP: Show other field instead of id

I'm working in a web aplication for board role playing games management. Its very simple for now.
I have 3 tables:
(1) Game
* id
* title
* user_id (game master)
(2) Sheet
* id
* name
* game_id
* user_id
(3) Users
* id
* username
Well, I have two problems:
1 - In Sheet view, i cant show the game tittle or the user name, just his id's
2 - In Game view, I cant show the user name (the game master).
I try a lot of answers found here for similar problems, but nothing works. I'm i little bit frustrated :( please help.
Here my code details:
MODELS:
/*User Model*/
class User extends AppModel {
public $name = 'User';
public $hasMany = array(
'Sheet' => array(
'className' => 'Sheet',
'foreignKey' => 'user_id'
),
'Game' => array(
'className' => 'Game',
'foreignKey' => 'user_id'
)
);
}
/*Game Model*/
class Game extends AppModel {
public $name = 'Game';
public $belongsTo = array(
'Master' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
public $hasMany = array (
'Chars' => array (
'className' => 'Sheet',
'foreignKey' => 'game_id'
)
);
}
/*Sheet Model*/
class Sheet extends AppModel {
public $name = 'Sheet';
public $belongsTo = array (
'Party' => array (
'className' => 'Game',
'foreignKey' => 'game_id'
),
'Player' => array (
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
CONTROLLERS:
/*SheetController*/
class SheetController extends AppController {
public $helpers = array('Html', 'Form');
var $name = 'Sheets';
public function view($id = null) {
$this->Sheet->id = $id;
$this->Sheet->recursive = 2;
if (!$this->Ficha->exists()) {
throw new NotFoundException(__('La ficha no existe'));
}
$this->set('sheet', $this->Sheet->read(null, $id));
}
}
class PartidasController extends AppController {
public $helpers = array('Html', 'Form');
var $name = 'Partidas';
public function view($id) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$this->Partida->recursive=2;
$partida = $this->Partida->findById($id);
if (!$partida) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('partida', $partida);
}
}
VIEWS:
/*Game View*/
<?php echo $game['Game']['title']; ?>
<strong>Master: </strong>
<?php
echo $this->Html->link($game['Game']['user_id'], array('controller' => 'Users','action' => 'view',$game['Game']['user_id'])); ?>
/*Sheet View*/
<?php echo $this->Html->link($sheet['Sheet']['nombreFicha'],array('controller' => 'sheets', 'action' => 'view', $sheet['Sheet']['id']));?>
<?php echo $this->Html->link($sheet['Sheet']['user_id'],array('controller' => 'users', 'action' => 'view', $sheet['Sheet']['user_id'])); ?>
<?php echo $this->Html->link($sheet['Sheet']['game_id'],array('controller' => 'games', 'action' => 'view', $sheet['Sheet']['game_id'])); ?>

CakePHP - Third Part Assignments

Sorry if the Title misses what i'm aiming at, but had no clue how to name this. Here's my Quest:
I have a single Cart, holding multiple Items (1:n) which are belonging to prices (1:1).
The Relations between Items and Prices are working as well:
class Item extends AppModel {
public $hasOne = 'Price';
}
class Price extends AppModel {
public $belongsTo = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'id'
)
);
}
But now i make a select (find) of a cart and want those items included, which is also working as well:
class CartItem extends AppModel {
public $useTable = 'cart_items';
public $belongsTo = array('Item', 'Address');
}
But what i really need is to get those prices of each item, which is not working ($result in afterFind()-Callback in Item-Model does not include the assigned prices & afterFind()-Callback in Price-Model is not called when finding a cart)..
what am i missing here?
/EDIT: Recent Changes:
class AppModel extends Model {
var $actsAs = array('Containable');
}
class CartsController extends AppController {
public function getCart() {
$cart = ClassRegistry::init('CartItem')->find('all', array(
'contain' => array(
'Item' => array(
'Price'
),
'Address'
),
'conditions' => array(
'id_cart' => $cart['Cart']['id']
)
));
}
The above changes cause that i'll get a Price into a found Item but only into the last one thats found.
You haven't shown your actual find(), but I suspect you're not setting an appropriate 'recursive' param or are not using 'contain'.
I prefer using the containable behaviour enabled from AppModel:
var $actsAs = array('Containable');
Then you can do something like:
$cartItem = $this->CartItem->find(
'first',
array(
'contain' => array(
'Item' => array(
'Price'
),
'Address'
),
'conditions' => array('CartItem.id' => 123)
)
);

Applying Limit on associated model Cakephp 2.3x HABTM

My Category Model:
class Category extends AppModel {
public $displayField = 'name';
// public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Post' => array(
'className' => 'Post',
'joinTable' => 'categories_postss',
'foreignKey' => 'category_id',
'associationForeignKey' => 'post_id',
'unique' => 'keepExisting'
)
);
}
$params['contain'] = array('Post' => array(
'limit'=> 3));
pr($this->Category->find('first',$params)); exit;
It is fetching all Posts, irrespective of limit.
What I want to do:
I have this page where I ma listing all the categories and latest 5 posts related to it.
I want to limit the associated model to only 5 rows.
Any ideas?
Containable behavior is not in use
The most likely reason for this problem is that the containable behavior is not being used at all.
Compare, for the below code example:
$results = $this->Category->find('first', array(
'contain' => array(
'Post' => array(
'limit' => 3
)
)
));
Without containable behavior, it'll generate the following queries:
SELECT ... FROM `crud`.`categories` AS `Category` WHERE 1 = 1 LIMIT
SELECT ... FROM `crud`.`posts` AS `Post`
JOIN `crud`.`categories_posts` AS `CategoriesPost` ON (...)
With containable behavior, it'll generate the following queries:
SELECT ... FROM `crud`.`categories` AS `Category` WHERE 1 = 1 LIMIT
SELECT ... FROM `crud`.`posts` AS `Post`
JOIN `crud`.`categories_posts` AS `CategoriesPost` ON (...) LIMIT 3
Given this (and the code in the question) check that the AppModel has the containable behavior in $actsAs:
<?php
// app/Model/AppModel.php
class AppModel extends Model {
public $actsAs = array('Containable');
}
Limit always required?
Alternatively, or possibly in addition, you may prefer to put a limit in the association definition - To do so just define the 'limit' key:
class Category extends AppModel {
public $hasAndBelongsToMany = array(
'Post' => array(
'limit' => 100, // default to a high but usable number of results
)
);
}
the hasAndBelongsToMany relationship seems unnecessary to me. I think you only need Category hasMany Post and Post belongsTo Category relationships. Add category_id to the posts table. Make both models actAs containable.
Post Model
class Post extends AppModel {
public $actsAs = array('Containable');
var $belongsTo = array(
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id'
),
// ... more relationships
);
Category Model
class Category extends AppModel {
public $actsAs = array('Containable');
var $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'category_id'
),
// ... more relationships
);
Categories Controller
class CategoriesController extends AppController {
public $paginate = array(
'Category' => array(
'contain' => array(
'Post' => array(
'limit' => 3
), // end Post
) // end Category contain
) // end Category pagination
); // end pagination
public function index() {
// for paginated results
$this->set('categories', $this->paginate());
// for find results
$this->Category->contain(array(
'Post' => array(
'limit' => 3
)
));
$this->set('categories', $this->Category->find('all'));
}

Categories