I'm making a little app for my softball team. I want to set up the following associations:
Model Game has two columns, away_id, home_id, both of which are aliases to Team.id.
In Game model I have:
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Home' => array(
'className' => 'Team',
'foreignKey' => 'home_id', // also tried simply 'id'
'conditions' => '',
'fields' => '',
'order' => ''
),
'Away' => array(
'className' => 'Team',
'foreignKey' => 'away_id', // also tried simply 'id'
'conditions' => '',
'fields' => '',
'order' => ''
)
);
In Team model I have:
public $virtualFields = ['home_id' => 'Team.id', 'away_id' => 'Team.id'];
And:
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'Game' => array(
'className' => 'Game',
'foreignKey' => 'home_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
// also tried only one 'Game' association with foreignKey => [home_id, away_id]
'Game' => array(
'className' => 'Game',
'foreignKey' => 'away_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
Getting the following error:
Note: "Psychouts" is the only non-self-explanatory appearance in the SQL below; it's the database name (and also my team name, henh).
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Team.id' in 'field list'
SQL Query: SELECT Game.id, Game.when, Game.cancelled, Game.field, Game.home_id, Game.away_id, Game.score_us, Game.score_them, Home.id, Home.captain_id, Home.name, Home.wins, Home.losses, Home.ties, Home.scored, Home.allowed, (Team.id) AS Home__home_id, (Team.id) AS Home__away_id, Away.id, Away.captain_id, Away.name, Away.wins, Away.losses, Away.ties, Away.scored, Away.allowed, (Team.id) AS Away__home_id, (Team.id) AS Away__away_id FROM psychouts.games AS Game LEFT JOIN psychouts.teams AS Home ON (Game.home_id = Home.id) LEFT JOIN psychouts.teams AS Away ON (Game.away_id = Away.id) WHERE 1 = 1 LIMIT 20
Following AD7six's comments, the solution which, after testing, seems correct is:
In Team model, erase the virtual fields I'd proposed and then define Game association as follows:
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Game' => array(
'className' => 'Game',
'foreignKey' => ['OR' => ['Game.home_id = Team.id', 'Game.away_id = Team.id']]
'conditions' => '',
'fields' => '',
'order' => ''
),
);
And in Game model, define Team association as usual:
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Team' => array(
'className' => 'Team',
'foreignKey' => 'id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
Related
I have a polymorphic association that I have set up it goes like this:
Media has a 1-to-1 association with either Photo, Video or Text
an excerpt of the Media model looks like this:
public $hasOne = array(
'Photo' => array(
'className' => 'Photo',
'foreignKey' => 'media_id',
'dependent' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'Text' => array(
'className' => 'Text',
'foreignKey' => 'media_id',
'dependent' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
Is there a way to specify a condition like
'conditions' => ['LfrMomentArticle.type' => 'photo'],
inside the Photo submodel so that it will not query over all the submodels each time but instead look at the type and then pick the correct submodel?
walking in the same shoes.
you can add the condition like:
'conditions' => ['LfrMomentArticle.type' => 'photo'],
if you have a type field in your LfrMomentArticle model(and of course in the db).
I'm trying to save some data using HasAndBelongsToMany relations.
Here are my tables :
commercials:
id (int) AI
name (varchar)
showrooms:
id (int) AI
name (varchar)
commercials_showrooms:
id (int) AI
commercial_id (int)
showroom_id (int)
And my models :
class Showroom extends AppModel
{
public $hasAndBelongsToMany = array(
'Commercial',
);
}
class Commercial extends AppModel
{
public $hasAndBelongsToMany = array(
'Showroom'
);
}
I'm trying to save data (hard coded for now) this way :
$this->loadModel('Showroom');
$this->Showroom->saveAll(array(
'Showroom' => array(
'id' => 1
),
'Commercial' => array(
'name' => 'test'
)
));
saveAll() returns (bool)true, however, nothing is saved in database.
How can I fix this ?
Did you read the section on "Saving Related Model Data (HABTM)" in the CakePHP book?
It suggests a different format than you're using for your data.
to test your table if is working try this in your controller:
$this->loadModel('CommercialsShowroom');
$CommercialsShowroom = array('CommercialsShowroom'=>array(
'commercial_id'=>your_value,
'showroom_id'=>your_value));
$this->CommercialsShowroom->create();
if ($this->CommercialsShowroom->save($CommercialsShowroom, false)){
var_dump('It is saved');
}
and for Model configuration read Dave link for more information
//CommercialsShowroom model:
var $belongsTo = array(
'Commercial' => array(
'className' => 'Commercial',
'foreignKey' => 'commercial_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Showroom' => array(
'className' => 'Showroom',
'foreignKey' => 'showroom_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
//Showroom model:
var $hasAndBelongsToMany = array(
'Commercial' => array(
'className' => 'Commercial',
'joinTable' => 'commercials_showrooms',
'foreignKey' => 'commercial_id',
'associationForeignKey' => 'showroom_id',
'unique' => true,
)
);
//Commercial model:
var $hasAndBelongsToMany = array(
'Showroom' => array(
'className' => 'Showroom',
'joinTable' => 'commercials_showrooms',
'foreignKey' => 'showroom_id',
'associationForeignKey' => 'commercial_id',
'unique' => true,
)
);
in my model 'mesn' i have belongsto relations:
public $belongsTo = array(
'Order' => array(
'className' => 'Order', 'foreignKey' => 'order_id', 'conditions' => '', 'fields' => '', 'order' => ''
), 'SaleOrder' => array(
'className' => 'SaleOrder', 'foreignKey' => 'sale_order_id', 'conditions' => '', 'fields' => '',
'order' => ''
), 'ShippedBox' => array(
'className' => 'Box', 'foreignKey' => 'shipped_box_id', 'conditions' => '', 'fields' => '',
'order' => ''
)
); /* * * hasMany associations** #var array
In one of my model-functions i want to join another table on the "belongsto" "ShippedBox" (table: boxes). But doesn't matter how i try to write the join i get an error message of unknown column:
$arr_s_result = $this->find('all', array(
'joins' => array(
array('table' => 'shipments',
'alias' => 'MyShipments',
'type' => 'INNER',
'conditions' => array(
'MyShipments.id = ShippedBox.shipment_id'
)
)),
'conditions' => array('Mesn.name' => $arr_search), 'recursive' => 0
));
I have tried:
'MyShipments.id = ShippedBox.shipment_id'
and
'MyShipments.id = box.shipment_id'
and even
'MyShipments.id = Boxes.shipment_id'
where the table "boxes" with the field "shipment_id" exists.
How can i get this join working?
'MyShipments.id = box.shipment_id'
to:
'MyShipments.id = Box.shipment_id'
Also what about this:
$arr_s_result = $this->find('all', array(
'conditions' => array('Mesn.name' => $arr_search), 'recursive' => 0
));
The belongsTo join is done automatically.
I think you'll need to do something like use subqueries to get what you want -
$arr_s_result = $this->find('all', array(
'joins' => array(
array('table' => '(SELECT boxes.id, [enter other fields you need here] FROM shipments JOIN boxes ON boxes.shipment_id = shipments .id)',
'alias' => 'MyShipments',
'type' => 'INNER',
'conditions' => array(
'Mens.shipped_box_id = MyShipments.id'
)
)),
'conditions' => array('Mesn.name' => $arr_search), 'recursive' => 0
));
My friend built a big form application in CakePHP. It has a central model called "Player" and a bunch of tables and models representing different categories of questions in the form. She asked me to help implementing Auth and we've been having some trouble. I was able to link User and Player together as per the Simple Authentication tutorial on the Cake website but I'm having trouble implementing Auth on the tables related to Player. The problem occurs on the "add"-like sections of the app. Before my implementation the add function looked like this:
public function name( $id =null) //Create the TEAM team name ,type
{
$this->Team->create();
//$this->request->data['Team']['user_id'] = $this->Auth->user('id');
if ($this->Team->save($this->request->data))
{
$idt=$this->Team->id;
$this->Session->setFlash(__('The Team' .$idt . ' has been saved'));
$this->redirect(array('action' => 'position', $idt));
}
else
{
$this->Session->setFlash(__('The Team could not be saved. Please, try again.'));
}
$players = $this->Team->Player->find('list' , array('conditions' => array('Player.id' => $id)));
$this->set(compact('players'));
}
Once this has been submitted a Team is created and the player_id is set. However when I uncomment the commented line where I read the user id, the player id does not write to the database which messes up every subsequent insertion. All tables have a column for both user_id and player_id although user does not have a column for player_id. Don't really know how relevant these are but here are the associations in the models:
User
public $hasOne = array(
'Player' => array(
'className' => 'Player',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
));
Player
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $hasMany = array(
'ContIllnessDetail' => array(
'className' => 'ContIllnessDetail',
'foreignKey' => 'player_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'ContInjuryDetail' => array(
'className' => 'ContInjuryDetail',
'foreignKey' => 'player_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'NewIllnessDetail' => array(
'className' => 'NewIllnessDetail',
'foreignKey' => 'player_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'NewInjuryDetail' => array(
'className' => 'NewInjuryDetail',
'foreignKey' => 'player_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'PreviousInjuryDetail' => array(
'className' => 'PreviousInjuryDetail',
'foreignKey' => 'player_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
and Team
public $hasOne = array(
'TrainingDetail' => array(
'className' => 'TrainingDetail',
'foreignKey' => 'team_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $belongsTo = array(
'Player' => array(
'className' => 'Player',
'foreignKey' => 'player_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
I also copied the isOwnedBy method into every model as per the Auth tutorial. Has anyone got any advice as to how I solve this?
I have a bunch of models with various associations set up between them and seems like Cakephp at times executes incorrect SQL statement and cause MySQL to barf.
For example, if I have two models, Comment and Tag and a code like this:
$this->Comment->id = 5;
$this->Comment->saveField('read_count', 3);
yields SQL statement:
UPDATE comments SET read_count = 3 WHERE Tag.id = 3;
It doesn't happen all the time but it eventually happens since I am doing everything in a tight loop.
Please help. This really makes me question my decision to go with Cake since this sounds bad.
Thanks.
EDIT 1
I just ran into the problem and here is the faulty SQL:
SELECT COUNT(*) AS `count` FROM `albums_songs` AS `AlbumSong` WHERE `ArtistGenre`.`id` = 26482
AlbumSong and ArtistGenre are two completely separate tables and they are not related at all.
EDIT 2
Just ran into another failure. The code is:
$this->Song->find('first', array('conditions' => array('Song.artist_id' => 30188, 'Song.name' => 'Pal Pal (By.Tarkhanz)'), 'fields' => array('Song.id')))
While the generated SQL is:
SELECT `Song`.`id` FROM `songs` AS `Song` WHERE `Artist`.`name` = 'Annie Villeneuve' LIMIT 1
As you can see no were in the conditions do I specify an Artist.name yet the SQL generated is looking at it.
EDIT 3
Another example failure. Call is as followed:
$this->Song->id = $song_id;
$library_count = $this->Song->field('Song.library_count');
Yet the SQL is:
SELECT `Song`.`library_count` FROM `songs` AS `Song` WHERE `Artist`.`name` = 'Mazikana_Ragheb_Allama' LIMIT 1
where Artist.name is not a column of Song as it belongs to the Artist model.
Thanks.
EDIT 4
models/album.php
<?php
class Album extends AppModel {
var $name = 'Album';
var $belongsTo = array(
'Artist' => array(
'className' => 'Artist',
'foreignKey' => 'artist_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $hasAndBelongsToMany = array(
'Song' => array(
'className' => 'Song',
'joinTable' => 'albums_songs',
'foreignKey' => 'album_id',
'associationForeignKey' => 'song_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
var $hasMany = array(
'AlbumSong' => array(
'className' => 'AlbumSong',
'foreignKey' => 'album_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
?>
models/album_song.php
<?php
class AlbumSong extends AppModel {
var $name = 'AlbumSong';
var $useTable = 'albums_songs';
var $belongsTo = array(
'Song' => array(
'className' => 'Song',
'foreignKey' => 'song_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Album' => array(
'className' => 'Album',
'foreignKey' => 'album_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
?>
models/artist.php
<?php
class Artist extends AppModel {
var $name = 'Artist';
var $hasMany = array(
'Album' => array(
'className' => 'Album',
'foreignKey' => 'artist_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'Song' => array(
'className' => 'Song',
'foreignKey' => 'artist_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'ArtistGenre' => array(
'className' => 'ArtistGenre',
'foreignKey' => 'artist_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
?>
models/artist_genre.php
<?php
class ArtistGenre extends AppModel {
var $name = 'ArtistGenre';
var $useTable = 'artists_genres';
var $belongsTo = array(
'Artist' => array(
'className' => 'Artist',
'foreignKey' => 'artist_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Genre' => array(
'className' => 'Genre',
'foreignKey' => 'genre_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
?>
models/genre.php
<?php
class Genre extends AppModel {
var $name = 'Genre';
var $hasAndBelongsToMany = array(
'Artist' => array(
'className' => 'Artist',
'joinTable' => 'artists_genres',
'foreignKey' => 'genre_id',
'associationForeignKey' => 'artist_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
var $hasMany = array(
'ArtistGenre' => array(
'className' => 'ArtistGenre',
'foreignKey' => 'genre_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
?>
models/song.php
<?php
class Song extends AppModel {
var $name = 'Song';
var $belongsTo = array(
'Artist' => array(
'className' => 'Artist',
'foreignKey' => 'artist_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/*
var $hasAndBelongsToMany = array(
'Album' => array(
'className' => 'Album',
'joinTable' => 'albums_songs',
'foreignKey' => 'song_id',
'associationForeignKey' => 'album_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
*/
var $hasMany = array(
'AlbumSong' => array(
'className' => 'AlbumSong',
'foreignKey' => 'song_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
?>
That is pretty much of it. For sake of brevity I removed validation
code.
Thanks a lot!
I have had possibly the same problem. The issue I encountered was cache collision in cake's implementation of caching the conditions (i.e. the WHERE clause) of a parsed sql.
For cake 1.3, the results of DboSource::conditions() and DboSource::name() are cached by default. see: DboSource. The cache uses crc32 hashing algorithm, which has a higher chance of collision. Also, running queries in a tight loop can also increase the chance of collision. That may explain why you have mismatching table names in the form of
select * from `table_A` where `table_B`.`field` ...
The solution was to set the data source to not do this caching. So, try
$ds = $this->Comment->getDataSource();
$ds->cacheMethods = false;
before using methods that generate sql statements.
Make sure not to have something like this:
class Tag extends AppModel
{
public $belongsTo = array (
'Comment' => array(
'conditions' => array(
'id' => 3, // Will add this condition on every query.
),
)
);
}
Not sure if this bug has anything to do with it, what version are you running:
[eb76ab9] Fixed issue where Model::saveAll() would incorrectly commit a transaction which was not started in that function call itself.
http://cakephp.org/changelogs/1.3.6
try sticking $this-ModelName->create() before you set the id and save / find. all that does is clear any other data that is hanging around. a bit of a hack, but if it works could provide some clues to the real problem.
I've been learning CakePHP in the last few months and this kind of thing occasionally drove me crazy. dogmatic's comment about using ->create() before your call can help if you've been using that model earlier in your function, it will reset the model's internal state so stale values don't interfere. That may not be your problem.
I agree with yvover and bancer that it's probably an issue of relationships. Posting your models (or links to the code) would be a big help. The thing that caught me more than once during development was thinking I was editing the model for a class when I was actually editing something else due to a name mismatch, so changes weren't reflected because my 'model' was never loaded.