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'])); ?>
Related
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);
I'm trying set association in cakephp
my db
two model:
namespace App\Model\Table;
class UsersTable extends Table {
public function initialize(array $config)
{
$this->hasOne('Scores',[
'className' => 'Scores',
'conditions' => '',
'dependent' => true
]);
}
}
and
class ScoresTable extends Table {
//var $name = 'Scores';
public final $connection = ConnectionManager::get('default');
public function initialize(array $config)
{
$this->belongTo('Users',
'foreignKey' => 'user_code_Student',
'joinType' => 'INNER',
);
}
}
function index in controller:
public function index() {
//$connection = ConnectionManager::get('default');
$modelUser = $this->loadModel('Users');
$dataUser = $modelUser->find('all')->contain(['Score']);
/*$data = array(
/*'listUser' => $modelUser->find('all', array(
'conditions' => array('email LIKE' => '%gmail.com'),
'limit' => 2
)),$connection
->execute('SELECT * FROM users WHERE email like :email limit 3', ['email' => '%gmail.com'])
->fetchAll('assoc')
'listUser' => $this->paginate($modelUser->find('all')),
'title' => 'Demo MVC'
);*/
$data = array(
'listUser' => $dataUser
);
$this->set('data', $data);
}
When I run it, the following error is shown: Users is not associated with Score
Can you help me?
Your relation looks like invalid.Try this:
users table
public function initialize(array $config)
{
$this->hasOne('Scores',[
'foreignKey' => 'user_code_Student'
]);
}
scores table
public function initialize(array $config)
{
$this->belongsTo('Users', // you wrote here belongTo that should be belongsTo instead
'foreignKey' => 'user_code_Student', // is user_code_Student foreignKey ???
'joinType' => 'INNER',
);
}
And also change this:
$dataUser = $modelUser->find('all')->contain(['Scores']); // not Score
I have two table rostertype and rostertypepositions
I have created two model
class Roster_type extends DataMapper{
var $table = "rostertype";
var $has_many = array(
'position' => array(
'class' => 'Roster_typeposition',
'other_field' => 'roster_position',
'join_self_as' => '',
'join_other_as' => 'RosterType'
)
);
function __construct($id = NULL){
parent::__construct($id);
}
function getAllRoster(){
return $this->count();
}
}
class Roster_typeposition extends DataMapper{
var $table = "rostertypepositions";
var $default_order_by = array('PositionIndex'=>'asc');
var $has_one = array(
'roster_position' => array(
'class' => 'Roster_type',
'other_field' => 'position',
'join_self_as' => 'RosterType',
'join_other_as' => ''
)
);
function __construct($id = NULL){
parent::__construct($id);
}
function get_all_positions(){
$u = $this->get_iterated();
foreach ($u as $ab=>$d){
echo "<pre>";print_r($d->roster_position->get());echo "</pre>";
}
die();
}
}
But for some reason i am getting this error
Error Number: 1146
Table 'ad_8cceab3cf7883a5.rostertype_rostertypepositions' doesn't exist
SELECT `rostertype`.*
FROM (`rostertype`)
LEFT OUTER JOIN `rostertype_rostertypepositions` position_rostertype_rostertypepositions ON `rostertype`.`id` = `position_rostertype_rostertypepositions`.`_id`
WHERE `position_rostertype_rostertypepositions`.`RosterType_id` = 2
Filename: /Applications/MAMP/htdocs/IBM_bluemix/Development/Draftbeast-Dev/libraries/Datamapper.php
Line Number: 1344
I dont know how it is generating that table position_rostertype_rostertypepositions. Please help and what am i doing wrong.
Solved it by taking empty fields in model
class Roster_typeposition extends DataMapper{
var $model = 'rostertypepositions';
var $table = "rostertypepositions";
var $default_order_by = array('PositionIndex'=>'asc');
var $has_one = array(
'roster_position' => array(
'class' => 'Roster_type',
'other_field' => 'position',
'join_self_as' => 'RosterType',
)
);
And
class Roster_type extends DataMapper{
var $model = 'Roster_type';
var $table = "rostertype";
var $has_many = array(
'position' => array(
'class' => 'Roster_typeposition',
'other_field' => 'roster_position',
'join_other_as' => 'RosterType'
)
);
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.
In CakePHP I've a model Customer which looks like this:
<?php
class Customer extends AppModel {
public $hasMany = array(
'Invoice' => array(
'className' => 'Invoice',
)
);
public function getDisplayName($id){
$customer = new Customer();
$customer_array = $customer->find('first', array(
'conditions' => array('Customer.id' => $id)
));
if($customer_array['Customer']['company']){
return $customer_array['Customer']['company'];
} else {
return $customer_array['Customer']['frontname'] . ' ' . $customer_array['Customer']['lastname'];
}
}
public function getFullName($id){
$customer = new Customer();
$customer_array = $customer->find('first', array(
'conditions' => array('Customer.id' => $id)
));
return $customer_array['Customer']['frontname'] . ' ' . $customer_array['Customer']['lastname'];
}
}
?>
In an other view (Project) I want to show a list of customers with there display name (because some of them have an company and others don't).
So in the ProjectController I added this:
$customers = $this->Project->Customer->find('list', array(
'fields' =>array(
'Customer.id', $this->Project->Customer->getDisplayName('Customer.id')
),
'conditions' => array(
'Customer.cloud_id' => '1'
)
));
$this->set('customers', $customers);
But then I get an MySQL error because the second field isn't a databasecolumn.
Who can help me with this question?
Your best best would be using virtual fields in your Customer model:
See the docs: http://book.cakephp.org/2.0/en/models/virtual-fields.html
<?php
class Customer extends AppModel {
public $hasMany = array(
'Invoice' => array(
'className' => 'Invoice',
)
);
public $virtualFields = array(
'display_name' => 'IF(Customer.company IS NOT NULL, Customer.company, CONCAT_WS(' ', Customer.frontname, Customer.lastname))'
);
}
?>
Then in projects controller:
<?php
$customers = $this->Project->Customer->find('list', array(
'fields' =>array(
'Customer.id', 'Customer.display_name'
),
'conditions' => array(
'Customer.cloud_id' => '1'
)
));
$this->set('customers', $customers);
?>
To answer the question more generally (here the virtual fields solutions works fine), you could rewrite the getDisplayName function and put in in your Controller.
Then you could call it from the view using
$displayName= $this->requestAction(array(
'controller'=>'CustomersController',
'action'=>'getDisplayName ')
);
echo $displayName;