Codeigniter datamapper one to many relationship - php

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'
)
);

Related

PrestaShop, Class not found in ModuleAdminController::getController

i'm trying to develop a PrestaShop module with controllers i placed, for example in:
/modules/mymodule/controllers/admin/myControlController.php
class MyControlController extends ModuleAdminController {
public function __construct() {
$this->module = 'mymodule';
$this->bootstrap = true;
$this->context = Context::getContext();
$token = Tools::getAdminTokenLite('AdminModules');
$currentIndex='index.php?controller=AdminModules&token='.$token.'&configure=mymodule&tab_module=administration&module_name=mymodule';
Tools::redirectAdmin($currentIndex);
parent::__construct();
}
public function showForm() {
die("hello");
}}
Controller works (construct method is called) if i call it form url
http://myshop.com/adminxxx/index.php?controller=MyControl&token=9faf638aa961468c8563ffb030b3c4a8
But i can't access methods of controller from main class of module:
ModuleAdminController::getController('MyControl')->showForm();
I received "Class not found" ever
Is that the correct method to access a control from outside?
Thanks!
If you want to show anything that concern a form you should use renderForm().
Your should try parent::showForm(); or $this->showForm();.
Here is an example of controller that can work :
require_once _PS_MODULE_DIR_.'modulename/models/ModuleNameLog.php';
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
class AdminModuleNameLogController extends ModuleAdminController
{
protected $_defaultOrderBy = 'id_modulenamelog';
protected $_defaultOrderWay = 'DESC';
public function __construct()
{
$this->table = 'modulenamelog';
$this->className = 'ModuleNameLog';
$this->context = Context::getContext();
$this->lang = false;
$this->bootstrap = true;
$this->actions_available = array();
$this->actions = array();
$this->show_toolbar = false;
$this->toolbar_btn['new'] = array();
$this->tabAccess['add'] = '0';
$this->allow_export = true;
$this->requiredDatabase = true;
$this->page_header_toolbar_title = $this->l('Example Module Name logs');
$this->_select = 'SUM(a.quantity) as total_quantity';
$this->_group = ' GROUP BY a.id_product, a.id_product_attribute ';
$this->fields_list = array(
'id_product' => array(
'title' => $this->l('Product'),
'align' => 'center',
'callback' => 'getProductName',
),
'id_product_attribute' => array(
'title' => $this->l('Combination'),
'align' => 'center',
'callback' => 'getAttributeName',
),
'total_quantity' => array(
'title' => $this->l('Total Quantity'),
'align' => 'center',
),
);
$this->mod = new ModuleName();
$this->mod->cleanLogs();
$this->context = Context::getContext();
parent::__construct();
}
public function getProductName($id)
{
if (!empty($id)) {
$product = new Product($id, true, $this->context->cookie->id_lang);
return $product->name;
}
}
public function getAttributeName($id)
{
if (!empty($id)) {
$combination = new Combination($id);
$names = $combination->getAttributesName($this->context->cookie->id_lang);
$str = array();
if (!empty($names)) {
foreach ($names as $value) {
$str[] = $value['name'];
}
}
return implode(' - ', $str);
} else {
return '-';
}
}
public function postProcess()
{
if (Tools::isSubmit('purge_id')) {
// Do something here
$id = (int) Tools::getValue('purge_id');
Tools::redirectAdmin(self::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModuleNameLog').'&conf=4');
}
parent::postProcess();
}
public function renderList()
{
$carts = Db::getInstance()->executeS('SELECT ct.*, cs.`firstname`, cs.`lastname` FROM '._DB_PREFIX_.'cart ct LEFT JOIN '._DB_PREFIX_.'customer cs ON ct.id_customer = cs.id_customer WHERE 1 ORDER BY id_cart DESC LIMIT 0,2000');
$tpl = $this->context->smarty->createTemplate(_PS_MODULE_DIR_.'modulename/views/templates/admin/preform.tpl');
$tpl->assign(array(
'carts' => $carts,
));
$html = $tpl->fetch();
return $html.parent::renderList();
}
public function renderForm()
{
if (!$this->loadObject(true)) {
return;
}
$obj = $this->loadObject(true);
if (isset($obj->id)) {
$this->display = 'edit';
} else {
$this->display = 'add';
}
$array_submit = array(
array(
'type' => 'select',
'label' => $this->l('Cart :'),
'name' => 'id_cart',
'options' => array(
'query' => Db::getInstance()->executeS('SELECT * FROM '._DB_PREFIX_.'cart WHERE id_cart > 0 ORDER BY id_cart DESC LIMIT 0,500'),
'id' => 'id_cart',
'name' => 'id_cart',
),
),
array(
'type' => 'text',
'label' => $this->l('Quantity translation here'),
'hint' => $this->l('Description and translation here'),
'name' => 'quantity',
),
);
$this->fields_form[0]['form'] = array(
'tinymce' => false,
'legend' => array(
'title' => $this->l('Form title'),
),
'input' => $array_submit,
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default',
),
);
$this->multiple_fieldsets = true;
return parent::renderForm();
}
}

List content of folder and child subfolders using CakePHP 2.x

I am trying to get content of folder and sub folders content in php mysql.
I have build a table to maintain folder structure as follows
And another table for media contents of the folder, which is as follows
On the first table I am maintining a parent_id to store parent folder id.
0 is for parent folder id.
Suppose I have 1,2,3 folders in root
4,5 inside 1.
6,7 inside 2
etc.
Media content table is storing contents for each folder_id.
Now I need to display the folder structure and contents in CakePHP.
I have gone to the first level of listing. as follows
$folderArr = $this->ProjectFolder->find('all',
array(
'conditions'=>
array(
'ProjectFolder.is_delete'=>'0',
'ProjectFolder.parent_id'=>$pid,
'ProjectFolder.user_id' => $userId
),
)
);
$folderContent = $this->ProjectMediaContent->find('all',
array(
'conditions'=>
array(
'ProjectMediaContent.project_folder_id'=>$pid,
),
)
);
//$log = $this->ProjectMediaContent->getDataSource()->getLog(false, false);
//debug($log);
//exit;
$content = Array();
if(!empty($folderContent)){
$mediapath = $thumbpath = '';
foreach($folderContent as $mediaContent){
if(!empty($mediaContent['ProjectMediaContent']['media'])){
$mediapath = Router::url('/', true).'files/folder/'.$mediaContent['ProjectMediaContent']['media'];
$thumbpath = Router::url('/', true).'files/folder/thumbs/'.$mediaContent['ProjectMediaContent']['media'];
}else{
$mediapath = $mediaContent['ProjectImage']['actual_url'];
$thumbpath = $mediaContent['ProjectImage']['thumb_url'];
}
$parentFolderContent[] = array(
"mediaId" => $mediaContent['ProjectMediaContent']['project_media_content_id'],
"mediaType" => $mediaContent['ProjectMediaContent']['media_type'],
'socialPlatForm'=> $mediaContent['ProjectImage']['image_source'],
'actualPath' => $mediapath,
'thumbPath' => $thumbpath,
'socialId' => $mediaContent['ProjectImage']['social_id'],
);
}
}
if(!empty($folderArr)){
foreach($folderArr as $val){
//print_r($this->getFolderListing($val['ProjectFolder']['project_folder_id'],$userId));die('jj');
$content[] = array(
'Folderid' => $val['ProjectFolder']['project_folder_id'],
'FolderName' => $val['ProjectFolder']['folder_name'],
);
}
}
Project Folder Model as follows
class ProjectFolder extends AppModel{
public $name = 'ProjectFolder';
public $primaryKey = 'project_folder_id';
public $displayField = 'folder_name';
public $actsAs = array('Containable');
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
);
public $hasMany = array(
'ProjectMediaContent' => array(
'className' => 'ProjectMediaContent',
//'dependent' => true,
//'exclusive' => true,
)
);
}
ProjectMediaContent Model as follows
class ProjectMediaContent extends AppModel{
public $name = 'ProjectMediaContent';
public $primaryKey = 'project_media_content_id';
//public $useTable = 'project_medias';
public $belongsTo = array(
'ProjectFolder' => array(
'className' => 'ProjectFolder',
'foreignKey'=>'project_folder_id'
),
'ProjectImage' => array(
'className' => 'ProjectImage',
'foreignKey'=>'project_image_id'
)
);
}
The following should fetch all the data you need:
$this->ProjectFolder->contain(array(
'ProjectMediaContent'=>'ProjectImage'
));
$folderArr = $this->ProjectFolder->find('theaded', array(
'conditions'=> array(
'ProjectFolder.is_delete'=>'0',
'ProjectFolder.user_id' => $userId
),
));
I would pass $folderArr to the view, instead of rearranging the data in the controller.

join multiple tables in CakePHP and retrive data [closed]

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.

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'])); ?>

Using function from model in view

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;

Categories