I'm at a loss here the situation is as follows i have 2 tables:
filter and widget (yes none cake table names which im not allowed to change)
Now filter belongs to widget and widget has many filters both models show up in pr() like this.
[name] => Filter
[useTable] => filter
[belongsTo] => Array
(
[Widget] => Array
(
[className] => Widget
[foreignKey] => id
[conditions] =>
[fields] =>
[order] =>
[counterCache] =>
)
)
and filter
[name] => Widget
[useTable] => widget
[hasMany] => Array
(
[Filter] => Array
(
[className] => Filter
[foreignKey] => widget
[conditions] =>
[fields] =>
[order] =>
[limit] =>
[offset] =>
[dependent] =>
[exclusive] =>
[finderQuery] =>
[counterQuery] =>
)
)
Now the problem is as follows when i do a simple:
pr($this->Filter->findById(1934));
or
pr($this->Widget->findById(1663));
I get an error:
Missing Database Table
Error: Table analyse_widgets for model Widget was not found in datasource default.
But when i use this code it works fine, but this is just to ugly to use evrytime i want to find something:
$this->Widget;
pr($this->Filter->findById(1934));
pr($this->Widget->findById(1663));
I have no idea how to get this working like it should be. Is it because of the none caketable names ? or is it something i forgot ?
This is what im loading the models with and clearing model cache had no influence:
App::uses('Analyse.Filter', 'Model');
App::uses('Analyse.Widget', 'Model');
$this->uses = array('Analyse.Widget', 'Analyse.Filter');
Any insight in the situation would be greatly appreciated
Try this...
App::uses('Filter', 'Model');
App::uses('Widget', 'Model');
$this->uses = array('Widget', 'Filter');
Add $useTable in your model ie.
public $useTable = 'widget';
public $useTable = 'filter';
Hope it will help you!
Seem's when you use a hasMany or belongsTo with custom tablenames cake still makes it's own models to rely on. Unless you recast them again just before a find function which happend whith: $this->Filter and $this->Widget
I made a workaround by putting this in the beforeFilter but its only needed when you use a relation with none cake table names.
$this->Filter->useTable = 'filter';
$this->Widget->useTable = 'widget';
Related
I have three tables
in Events table
id
event_name
patient_id
madical_case_id
fees
in madicalCases table
id
patient_id
case_type
date
in Patients table
id
name
address
now i try to find all Events with bind(madicalCases and Patients).
but not getting succsess
**i try this**
$this->belongsTo('Patients', ['foreignKey' => 'patient_id', 'joinType' => 'INNER']);
$this->belongsTo('MadicalCases', ['foreignKey' => 'madical_case_id', 'joinType' => 'INNER']);
$event = $this->Events->find()->where(['patient_id' => $patient_id], ['madical_case_id' => $mc_id])->all();
OR
$this->belongsTo('MadicalCases', ['foreignKey' => 'madical_case_id', 'joinType' => 'INNER','Patients', ['foreignKey' => 'patient_id', 'joinType' => 'INNER']]);
$event = $this->Events->find()->where(['patient_id' => $patient_id], ['madical_case_id' => $mc_id])->all();
here some error
Call to undefined method App\Controller\EventsController::belongsTo() in E:\wamp\www\Gurukrupa\src\Controller\EventsController.php on line 36
Unable to emit headers. Headers sent in file=E:\wamp\www\Gurukrupa\src\Controller\EventsController.php line=36 [CORE\src\Http\ResponseEmitter.php, line 48]
Cannot modify header information - headers already sent by (output started at E:\wamp\www\Gurukrupa\src\Controller\EventsController.php:36) [CORE\src\Http\ResponseEmitter.php, line 149]
Cannot modify header information - headers already sent by (output started at E:\wamp\www\Gurukrupa\src\Controller\EventsController.php:36) [CORE\src\Http\ResponseEmitter.php, line 181]
$this->paginate = ['contain' => ['Patients', 'MadicalCases']];
$events = $this->Events->find('all')->where(['Events.patient_id' => $patient_id])->where(['Events.madical_case_id' => $madical_case_id]);
$allevents = $this->paginate($events);
Ohh man, you tried to break well design beauty of MVC framework. You can't bindModel or unbindModel in controller for CakePHP Version 3. They no longer support in V3. It must be done via Table object. Now, you tried to call belongTo in controller. Check detail here and it can be done something like this.
class MadicalCasesTable extends Table{
public function initialize(array $config){
$this->belongsTo('Patients')
->setForeignKey('patient_id')
->setJoinType('INNER');
}
}
I've been searching for all types of solutions and it's not working. I have two models, Bredbook and Genre, in bredbook.php and genre.php, associated with HABTM. No way to save the association.
Here is the code of one model:
public $hasAndBelongsToMany = array('Bredbook' => array('className' => 'Bredbook',
'joinTable' => 'bredbooks_genres',
'foreignKey' => 'genre_id',
'associationForeignKey' => 'bredbook_id'));
Here is the form:
echo $this->Form->create('Bredbook', array('action' => 'firstConnection'));
echo $this->Form->input('Genre', array('options' => $genres, 'empty' => false));
echo $this->Form->end('Validate');
And in BredbooksController.php:
if ($this->request->data)
{
if($this->Bredbook->saveAssociated($this->request->data))
return $this->redirect('/bredbooks/index');
}
The creation of the bredbook is ok, but no association is created in the table bredbooks_genres. I've tried everything... any help will be welcome.
You need to send Bredbook.id in your data array:
<?php
echo $this->Form->create('Bredbook');
//It can be any other attribute, but need some Breedbook data
echo $this->Form->input('Bredbook.id', array('value' => $id));
echo $this->Form->input(
'Genre',
array(
'options' =>$genres,
'empty' => false
)
);
echo $this->Form->end('Validate');
Or make sure your $this->request->data looks similar to this before saving:
Array
(
[Bredbook] => Array
(
//It can be any other attribute, but need some Breedbook data
[id] => 1
)
[Genre] => Array
(
[Genre] => Array
(
[0] => 1
)
)
)
This Solution will work also work when you are creating a new Bredbook as long as you send some data of that Model, it doesn't need to be the id, you can also send name or other attributes from your Bredbook Model. If you send Bredbook.id it will not create a new record and only make the associations, but if you don't send the id and send other attributes (like name for example) it will create a new record and will associate it with the Genre data your are sending.
I finally did it: I don't know if it's a necessary thing, but I just used cake bake to generate everything: http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html
Now I need some work to rearrange all the views, but my saving is working, with the exact same code I posted first, and I think I saved some time too with all that generated behaviour I needed !
I got a Table Users and a Table Groups. Every group has one GroupLeader.
So the field i use in is groupLeader ($hasOne) which contains a foreign key of users.
I cant manage to get that relation. So my question is, how to define a relation on a field with a diffent name.
thanks for a hint.
endo
You model should looks:
class Group extends AppModel
{
public $name = 'Group';
public $belongsTo = array('GroupLeader' => array(
'className' => 'User',
'foreignKey' => 'groupLeader'
)
);
}
Try with the above code. And ask if it is not worked for you.
I have this model and controller and it returns fine if it is a hasOne relationship but now DishCategory hasMany dishes. When I change the code below to hasMany it gives me an error saying Dish.id is not a known column while if it is a hasOne it works fine. How can I make it so that it returns all the Dish.id's that have id=1? (still using the join).
class DishCategory extends AppModel{
public $hasOne = array(
'Dish' => array(
'className' => 'Dish',
'foreignKey' => 'dish_category_id'
)
);
}
class DishCategoriesController extends AppController {
function get_categories($id)
{
// find category with a dish of $id
$this->set('dishes', $this->DishCategory->find('all', array(
'conditions' => array(
'Dish.id' => $id
)
)));
// set master layout
$this->layout = 'master_layout';
}
}
hasOne relations can be joined into the primary SQL query. hasMany relations cannot and need to be queried in a separate query. The conditions you specify for the query only apply to the primary query, all separate relational queries are build just based on the ids retrieved in the primary query. Set debug to 2 and have a good look at the query log to see what I mean.
To find the category of a dish, fetch the dish and look at its related category record:
$dish = $this->Dish->find('first', array('conditions' => array('Dish.id' => $id)));
echo $dish['DishCategory']['name'];
Since I take it that a dish belongsTo one category, your query "find all categories which have a dish with id x" makes little sense; there should only be one anyway.
I've got the field country_id in one of my models and instead of creating a countries table which contains a list of countries that doesn't change, what's the best approach to this?
I'm thinking about using a model without a database table but I don't know how to implement this.
Please help. Thanks in advance!
you can totaly use the no table syntax:
class ModelWithoutTable extends AppModel
{
var $useTable = false;
}
to have this Country Model tableless, but you need to mock a data source (i.e. XML,YAML,PHP Array and etc) for the countries data.
Hope this helps.
I would suggest using ArraySource from the community-maintained CakePHP Datasources plugin:
CakePHP 1.3.x - see master branch
CakePHP 2.x - see 2.0 branch
Download the entire plugin and extract the contents to app/plugins/datasources.
Define a connection to the datasource in app/config/database.php:
public $array = array('datasource' => 'Datasources.array');
This should allow you to emulate a table by defining records in your model:
class Country extends AppModel {
public $useDbConfig = 'array';
public $records = array(
array('id' => 1, 'name' => 'Test record')
);
}
As alternative, if there's no other data attached to the country besides, basically, an id of what country it is, you can probably keep it within the same model without association. Something along the lines of:
class MyModel extends AppModel {
public static $countries = array(
'Africa', 'America', ..., 'Zululand'
);
public $validate = array(
'country' => array(
'rule' => array('inList', self::$countries),
...
)
)
}