Create temporary table in CakePHP and load it as a Model - php

My plan is to create a temporary table using the $this->Model->query(); method then load it as a Model but I'm getting an error staying "Missing Database Table". Turning on debug to level two shows that the temporary table is success fully created but for some reason, when I try and load it as a model it doesn't work. It looks like cake doesn't even try to see if the table exists as there is no "SHOW FULL COLUMNS FROM ...' query being displayed. Not sure how to force cake to check for its existence.
$tmpModel = 'tempModel';
$tmpTable = 'temp_models';
$this->Model->query('CREATE TEMPORARY TABLE `'.$tmpTable ... );
$this->loadModel($tmpModel);
Thanks in advance.

$tmpModel = 'TempModel'; // CamelCase
also try, ClassRegisty::init($tmpModel);
final issue may be cache. but dont think so

Ok, after looking around a bit I have found a solution that works.
The problem was that Cake had already loaded the models caches at page load so used them as reference to the existence of a table. To resolve this problem I used "App::import('Model', $tmpModel);" which created the new modelCache allowing the loadModel script to run successfully.
$tmpModel = 'tempModel';
$tmpTable = 'temp_models';
$this->Model->query('CREATE TEMPORARY TABLE `'.$tmpTable ... );
App::import('Model', $tmpModel);
$this->loadModel($tmpModel);
Thanks anyway

After doing google for an hour .. finally found a way to have Model on Temporary table and it works like a charm
http://web2.0goodies.com/blog/uncategorized/mysql-temporary-tables-and-cakephp-1-3/

Related

copy record with all relations laravel 5.4

i have to copy a record from db
I am trying this
$new_p = $p->replicate();
$new_p->save();
but Its not saved
P model has many relations i dont know how to copy all !
You have to attach the many to many relationships to the clone after saving it, something like this:
$new_p = $p->replicate();
$new_p->save();
$new_p->firstRelations()->attach($p->firstRelations);
$new_p->secondRelations()->attach($p->secondRelations);

AR in Yii add duplicate rows

I have common model, which is generated by gii.
3 columns in mySql: id (int, A_I), setting(tinytext, null) and value(tinitext, null).
After this:
$cfg = new Config();
$cfg->setting = "sdd";
$cfg->value = 'dsf';
$cfg->save();
This effect I get even if create absolutely clear, new table and model.
This code runs in defaultAction.
Yii 1.1.4
PHP 5.5
MySQL 5.6.12
Help me, I'm tired search this bug =)
You said that the code runs in defaultAction. Is possible that you are calling it also in some other action. This way, the code runs twice.

Preventing Laravel adding multiple records to a pivot table

I have a many to many relationship set up and working, to add an item to the cart I use:
$cart->items()->attach($item);
Which adds an item to the pivot table (as it should), but if the user clicks on the link again to add an item they have already added it creates a duplicate entry in the pivot table.
Is there a built in way to add a record to a pivot table only if one does not already exist?
If not, how can I check the pivot table to find if a matching record already exists?
You can also use the $model->sync(array $ids, $detaching = true) method and disable detaching (the second param).
$cart->items()->sync([$item->id], false);
Update:
Since Laravel 5.3 or 5.2.44, you can also call syncWithoutDetaching:
$cart->items()->syncWithoutDetaching([$item->id]);
Which does exactly the same, but more readable :)
You can check the presence of an existing record by writing a very simple condition like this one :
if (! $cart->items->contains($newItem->id)) {
$cart->items()->save($newItem);
}
Or/and you can add unicity condition in your database, it would throw an exception during an attempt of saving a doublet.
You should also take a look at the more straightforward answer from Barryvdh.
#alexandre Butynsky method works very well but use two sql queries.
One to check if cart contains the item and one to save.
To use only one query use this:
try {
$cart->items()->save($newItem);
}
catch(\Exception $e) {}
As good as all this answers are because I had tried them all, one thing is still left unanswer or not taken care of: the issue of updating a previously checked value (unchecked the checked box[es]). I do have something similar to the above question expect i want to check and uncheck features of products in my product-feature table (the pivot table). I am a newbie and I have realised none of the above did that. The are both good when adding new features but not when i want to remove existing features (i.e. uncheck it)
I will appreciate any enlightenment in to this.
$features = $request->get('features');
if (isset($features) && Count($features)>0){
foreach ($features as $feature_id){
$feature = Feature::whereId($feature_id)->first();
$product->updateFeatures($feature);
}
}
//product.php (extract)
public function updateFeatures($feature) {
return $this->features()->sync($feature, false);
}
or
public function updateFeatures($feature) {
if (! $this->features->contains($features))
return $this->features()->attach($feature);
}
//where my attach() is:
public function addFeatures($feature) {
return $this->features()->attach($feature);
}
Sorry guys, not sure is I should delete the question because having figure out the answer myself, it sounds a bit stupid, well the answer to the above is as simple as working #Barryvdh sync() as follows; having read more and more about:
$features = $request->get('features');
if (isset($features) && Count($features)>0){
$product->features()->sync($features);
}
There are some great answers posted already. I wanted to throw this one out here as well though.
The answers from #AlexandreButynski and #Barryvdh are more readable than my suggestion, what this answer adds is some efficiency.
It retrieves only the entries for the current combination (actually only the id) and it than attaches it if it does not exist. The sync method (even without detaching) retrieves all currently attached ids. For smaller sets with little iterations this will hardly be a difference, ... you get my point.
Anyway, it is definitely not as readable, but it does the trick.
if (is_null($book->authors()->find($author->getKey(), [$author->getQualifiedKeyName()])))
$book->authors()->attach($author);
I just had this problem and was able to solve it.
For future readers: instead of using atach() you can use
syncWithoutDetaching()
This will make sure you do not get any duplicates!
There are more alternatives to attach()
That might be usefull in the laravel documentation
Note that this is not for Laravel 4
$branch->permissions()->syncWithoutDetaching([1,2,3]);

Cannot insert to my new table

I have created a migration for ratings, and the table also working when i am entering phpmyadmin.
The problem is, i cannot figure out, how to write to the table?
I am running the code from "story" controller
I am using this:
$z = new Rating();
$z->story_id = 10;
$z->save();
print_r($z);
My "ratings.php" model:
<?php
class Rating extends Eloquent {
protected $table = 'ratings';
}
?>
Is there some place where i should notify laravel that new Rating() means my table "ratings"?
It doesn't seem like i have done the migration correctly, but i am completely new still, so hope someone can figure it out for me.
well instead of using the save() function for laravel you can use the insert() function
Rating->insert_get_id(array('story_id' => '10'));
or
$insert_id = Rating->insert_get_id(array('story_id' => '10'));
for insertion into table.This is much easy to use and I have used this in my whole project and so far I haven't face any problems.
Also if you have not created the model for rating table then go to the models folder under application folder and create a file name rating.php and inside the file write this:
class Rating extends Eloquent
{
public static $timestamps = false;
}
Also please note that table which you created in the phpmyadmin should have name of the form "ratings".
I hope this can be of some help.
I don't really understand what you're doing. Are you trying to write into the table from php? Is Rating a sort of database connection class? You need to create a mysqli object to connect to the database, write a query, and get a result. For best security use a prepared statement. Mysqli Documentation Sorry if I'm off-base about your question, I'm just not positive about what it is.

Memcache with Symfony/Doctrine is reloading data

In my symfony project, I have a "complex" query that looks like:
$d = Doctrine_Core::getTable('MAIN_TABLE')
// Create the base query with some keywords
->luceneSearch($keywords)
->innerJoin('w.T1 ws')
->innerJoin('ws.T2 s')
->innerJoin('w.T3 piv')
->innerJoin('piv.T4 per')
->innerJoin('w.T5 st')
...
->innerJoin('doc.T12 docT')
->innerJoin('w.Lang lng')
->execute();
I added all those innerJoin to reduce the number of query due to my data model. Actually all data are recovered with this only query.... but the query took from 2 to 20 sec. depends on keywords.
I decided to use memcache because data are not changing all the time.
What I've done is configuring memcache and adding
...
->useResultCache(true)
->execute();
to my query.
What is strange is that :
The first time (when the cache is empty/flushed), only one query is execute
The second time, ~130 ares executed and it take more time than the first...
Those "new" queries are retrieving data from "inner join" for each record.
What I don't undestand is why "innerjoined" data are not saved in the cache?
I tried to change the hydrate mode but it seems not to be influent.
Someone has an idea?
After a whole day to googlise, to analyse doctrine and become desperate, I found an article that explain the solution:
class User extends BaseUser{
public function serializeReferences($bool=null)
{
return true;
}
}
The problem was the profile object was not getting stored in the result cache and thus causing a query each time it was called from the user object. After much hunting around, a long time in #doctrine, and a few leads from a couple of people, it turns out, by default, Doctrine will only serialize the immediate relation to the main object. However, you can make it so that it will serialize objects further down the line by overriding the function serializeReferences to return true in the class you want to serialize references from. In my example this is the User class. Since our application will never only need the ‘User’ class to be serialized on a result cache I completely overrode the function and made it always return true
http://shout.setfive.com/2010/04/28/using-doctrine-result-cache-with-two-deep-relations/

Categories