I am finding problem in getting the saved property after new insertion in model.
Model :
<?php
abstract class BaseTeacher extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('teacher');
$this->hasColumn('id', 'integer', null, array(
'unique' => true,
'primary' => true,
'type' => 'integer',
'autoincrement' => true,
));
$this->hasColumn('website', 'string', 512, array(
'type' => 'string',
'autoincrement' => true,
'length' => '512',
));
$this->hasColumn('doj', 'date', null, array(
'primary' => true,
'type' => 'date',
));
$this->hasColumn('isPermanent', 'boolean', null, array(
'default' => 0,
'type' => 'boolean',
));
$this->hasColumn('isTeaching', 'boolean', null, array(
'default' => 0,
'type' => 'boolean',
));
$this->hasColumn('empId', 'string', 512, array(
'type' => 'string',
'length' => '512',
));
$this->hasColumn('qualification', 'string', 512, array(
'type' => 'string',
'length' => '512',
));
$this->hasColumn('prevExperience', 'clob', null, array(
'type' => 'clob',
));
$this->hasColumn('status', 'string', 32, array(
'type' => 'string',
'length' => '32',
));
$this->hasColumn('college_id', 'integer', null, array(
'type' => 'integer',
));
$this->hasColumn('user_id', 'integer', null, array(
'type' => 'integer',
));
}
public function setUp()
{
parent::setUp();
$softdelete0 = new Doctrine_Template_SoftDelete(array(
'name' => 'deleted',
'type' => 'boolean',
'options' =>
array(
'default' => 0,
'notnull' => true,
),
));
$timestampable0 = new Doctrine_Template_Timestampable(array(
'created' =>
array(
'name' => 'created_at',
'type' => 'timestamp',
),
'updated' =>
array(
'name' => 'updated_at',
'type' => 'timestamp',
),
));
$this->actAs($softdelete0);
$this->actAs($timestampable0);
}
}
**Here is my code : **
$teacher = new Teacher();
$teacher->college_id = $collegeId;
$teacher->user_id = $user->id;
$teacher->save();
print_r($teacher->id);
It's pushing new entry in DB but not giving me the new generated row's property.
This is a weird query but honestly this killed my time.
How aweful, I just regenerated models with YML and it worked.
Related
I've added product with custom options programmatically. When I edit the product & save the added custom options deleted from saved product.
Below is my code to insert product with custom options:
$p = array(
'sku_type' => 0,
'sku' => 'SKU00'.$row['Pid'],
'name' => $row['ProductName'],
'description' => $row['Description'],
'short_description' => $row['Description'],
'type_id' => 'simple',
'attribute_set_id' => 4,
'weight' => 0.00,
'visibility' => 4,
'price_type' => 0,
'price_view' => 0,
'price' => $row['SPrice'],
'status' => 1,
'created_at' => strtotime('now'),
'category_ids' => 2,
'store_id' => 1,
'website_ids' => 1,
'tax_class_id' => 0,
);
$product->setData($p);
$optionRawData = array();
$optionRawData[0] = array(
'required' => 1,
'option_id' => '',
'position' => 0,
'type' => 'select',
'title' => $row['ProductName'],
'default_title' => $row['ProductName'],
'delete' => '',
);
$selectionRawData = array();
$selectionRawData[0] = array();
$selectionRawData[0][] = array(
'product_id' => $row['Product_Id'],
'selection_qty' => 1,
'selection_can_change_qty' => 100,
'position' => 0,
'is_default' => 1,
'selection_id' => '',
'selection_price_type' => 0,
'selection_price_value' => $row['SPrice'],
'option_id' => '',
'delete' => ''
);
$product->setCanSaveConfigurableAttributes(false);
$product->setCanSaveCustomOptions(true);
// Set the Bundle Options & Selection Data
$product->setBundleOptionsData($optionRawData);
$product->setBundleSelectionsData($selectionRawData);
$product->setCanSaveBundleSelections(true);
$product->setAffectBundleProductSelections(true);
$product->getResource()->save($product);
$productID = $product->getId();
$product = Mage::getModel('catalog/product')->load($productID);
$optionsArray = array(
array(
'title' => 'Standard',
'price' => 0.0,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => 0,
),
array(
'title' => 'Premium',
'price' => 10,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => 1,
),
array(
'title' => 'Deluxe',
'price' => 20,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => 2,
)
);
$options = array(
'title' => $product->getName(),
'type' => 'radio',
'is_required' => 1,
'sort_order' => 0,
'values' => $optionsArray,
);
$optionInstance = $product->getOptionInstance()->unsetOptions();
$product->setHasOptions(1);
$optionInstance->addOption($options);
$optionInstance->setProduct($product);
$product->save();
I update an entity (so same id) and I get a validation error on a field which has a 'unique' rule.
I verified in the db that there is no an existing identical field and so I don't understand why I have this error as I update the record so obviously the field exists already because it's itself!
Is it a problem to have a 'unique' rule on patchEntity()?
[
'site_name' => '...',
'datas' => object(App\Model\Entity\User) {
'id' => (int) 653,
'owner_id' => (int) 611,
'extraemails' => [
],
'owner' => object(App\Model\Entity\Owner) {
'id' => (int) 611,
'company' => 'This is the Company name',
'created' => object(Cake\I18n\Time) {
'time' => '2015-06-06T18:07:17+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-06-17T02:44:36+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'[new]' => false,
'[accessible]' => [
'email' => true,
'phone' => true,
'phone2' => true,
'fax' => true,
'company' => true,
'tva_number' => true,
'address' => true,
'postcode' => true,
'city' => true,
'country_id' => true,
'users' => true,
'username' => true,
'origin' => true
],
'[dirty]' => [
'email' => true,
'phone' => true,
'postcode' => true,
'city' => true
],
'[original]' => [
'email' => '...',
'phone' => '...',
'postcode' => '...',
'city' => '...'
],
'[virtual]' => [],
'[errors]' => [
'company' => [
'unique' => 'This company name exists already.'
]
],
'[repository]' => 'Owners'
},
....
EDIT patchEntity() call added
$user = $this->Users->patchEntity($site->users[0], [
'email' => $this->siteDatas['userEmail'],
'phone' => $this->siteDatas['ownerPhone'],
'role' => 'owner',
'active' => 1,
'extraemails' => $this->siteDatas['extraemails'],
'owner' => [
'company' => $this->siteDatas['ownerName'],
'email' => $this->siteDatas['ownerEmail'],
'phone' => $this->siteDatas['ownerPhone'],
'address' => $this->siteDatas['ownerAddress'],
'postcode' => $this->siteDatas['ownerPostcode'],
'city' => $this->siteDatas['ownerCity'],
'country_id' => $this->siteDatas['countryId'],
'web' => $this->siteDatas['ownerWeb'],
'origin' => 'sitra',
],
],
[
'validate' => 'import',
'associated' => [
'Extraemails',
'Owners' => [
'validate' => 'import'
]
]
]);
if ($user->errors()) {
// Here is where I get the 'unique' error
}
So again I verified that no other record in the table have the same 'company' name.
and as you can see in the debug() at the begining of my post, I have a owner->id and it's really the one I want to modify.
Here is the validator
public function validationImport(Validator $validator) {
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create')
->notEmpty('company')
->add('company', 'unique', ['rule' => 'validateUnique', 'provider' => 'table', 'message' => __("This company exists already.")])
...
])
;
return $validator;
}
//in my model
public function initialize (array $config)
{
$this->addBehavior('Timestamp');
$this->belongsTo('Users');
}
//in my controller
$query = $this->Articles->find('all')->contain(['users']);
/src/Controller/ArticlesController.php (line 39)
object(Cake\ORM\Query) {
'sql' => 'SELECT Articles.id AS `Articles__id`, Articles.title AS `Articles__title`, Articles.body AS `Articles__body`, Articles.created AS `Articles__created`, Articles.modified AS `Articles__modified`, Articles.is_delete AS `Articles__is_delete`, Articles.user_id AS `Articles__user_id`, Users.id AS `Users__id`, Users.username AS `Users__username`, Users.password AS `Users__password`, Users.role AS `Users__role`, Users.created AS `Users__created`, Users.modified AS `Users__modified` FROM articles Articles LEFT JOIN users Users ON Users.id = (Articles.user_id)',
'params' => [],
'defaultTypes' => [
'Articles.id' => 'integer',
'id' => 'integer',
'Articles.title' => 'string',
'title' => 'string',
'Articles.body' => 'text',
'body' => 'text',
'Articles.created' => 'datetime',
'created' => 'datetime',
'Articles.modified' => 'datetime',
'modified' => 'datetime',
'Articles.is_delete' => 'integer',
'is_delete' => 'integer',
'Articles.user_id' => 'integer',
'user_id' => 'integer'
],
'decorators' => (int) 0,
'executed' => false,
'hydrate' => true,
'buffered' => true,
'formatters' => (int) 0,
'mapReducers' => (int) 0,
'contain' => [
'users' => []
],
'matching' => [],
'extraOptions' => [],
'repository' => object(App\Model\Table\ArticlesTable) {
'table' => 'articles',
'alias' => 'Articles',
'entityClass' => 'App\Model\Entity\Article',
'associations' => [
(int) 0 => 'users'
],
'behaviors' => [
(int) 0 => 'Timestamp'
],
'defaultConnection' => 'default',
'connectionName' => 'default'
}
}
You are debugging the query and not the result. To see the contents you can try:
debug($query->toArray())
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.