Copy a model to another database in symfony 1.4 - php

Using Symfony 1.4 and doctrine I'd like to save a retrieved model to a different database connection:
retrieve model from master-database
change database connection to slave-database
save the model to the slave-database
I have the 2 connections defined in databases.yml.
here in pseudo-code:
$model = [retrieved from master-database];
$slaveConnection = Doctrine_Manager::getInstance()
->getConnection('slave-connection');
$model->save($slaveConnection);
If I create a new model, $model=new model(); the "code" above successfully saves the model to the slave-connection.
What is going wrong?
According to the Symfony log, Symfony recognizes the model as existing and issues an update (instead of an insert).
UPDATE model SET updated_at = '2011-10-21 17:37:32' WHERE id = '1';
Although Symfony is using the correct database connection ('slave-connection'), the update fails because the model isn't present in the slave-database, yet.
And the insert into the slave-database should use all values of the model, not only the changed ones, too.
Anyone can point me to the right direction to save an existing model to a different database?
edit with my solution.
Thanks samura!
Just some additions:
After performing deep copy Symfony saved a new id. But I wanted to really clone the model object to the slave db and so, I had to modify the id.
That caused unique constraint exceptions, so I had to delete first. So this is it:
$id = $model->getId();
$slaveConnection->execute("delete from modeltable where id=".$id);
$model_copy = $model->copy(true); # deep copy
$model_copy->setId($id);
$model_copy->save($slaveConnection);
hope this helps if someone else stumbles.

You could use the public function copy($deep = false) method of the Doctrine_Record class.
$model = [retrieved from master-database];
$slaveConnection = Doctrine_Manager::getInstance()
->getConnection('slave-connection');
$model_copy = $model->copy(true); # deep copy
$model_copy->save($slaveConnection);

Related

Doctrine Error saving two records at once (new entity was found through the relationship)

When I want to save 1 record to the database, everything works correctly.
When I want to save 2 records right after each other - an error occurs:
[Doctrine\ORM\ORMInvalidArgumentException]
A new entity was found through the relationship 'App\Entity\User#directory' that was not configured to cascade persist
operations for entity:. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity
or configure cascade persist this association in the mapping for example #ManyToOne(..,cascade={"persist"}). If you
cannot find out which entity causes the problem implement 'Main\Entity\Directory#__toString()' to get a clue.
I just started learning symfony and can't figure out what the problem is.
In my case: I create a new user who takes certain information from a directory that is already in my database.
For example, my new user is a cat lover, then the entry "loves cats" should pull up from the directory.
The text of the error says that I have to set up a connection and save a new record about the love of cats. But my reference book is already full, it does not need to be supplemented, just take information from there.
When I create one user, everything is fine. When I create two users who are supposed to take information from the directory and save the data, an error occurs.
Help me please.
I tried in different places to use method: $this->em->clear(). But it did not help.
class User:
ManyToOne(targetEntity="App\Entity\Directory")
JoinColumn(nullable=true)
private $directory;
public function createData($data) {
$this->setData($data);
$this->em->flush();
}
public function setData($data) {
$user = new User();
$directory = $this->em->getRepository(Directory::class)->findOneBy(['id' => $data['id']]);
$user->setDirectory($directory);
return $this;
}
You need to configure cascade operations for Directory entity which relates to user. Or you can do $em->persist($directory) before flushing

Symfony Doctrine Prevent Particular Entity's Record Deletion

imagine I have some doctrine Entity and I can have some records of this entity in the database which I dont want to be deleted, but I want them to be visible.
In general I can have entities, for which I have default records, which must stay there - must not be deleted, but must be visible.
Or for example, I want to have special User account only for CRON operations. I want this account to be visible in list of users, but it must not be deleted - obviously.
I was searching and best what I get was SoftDeletable https://github.com/Atlantic18/DoctrineExtensions/blob/v2.4.x/doc/softdeleteable.md It prevents fyzical/real deletion from DB, but also makes it unvisible on the Front of the app. It is good approach - make a column in the Entity's respective table column - 1/0 flag - which will mark what can not be deleted. I would also like it this way because it can be used as a Trait in multiple Entities. I think this would be good candidate for another extension in the above Atlantic18/DoctrineExtensions extension. If you think this is good idea (Doctrine filter) what is the best steps to do it?
The question is, is this the only way? Do you have a better solution? What is common way to solve this?
EDIT:
1. So, we know, that we need additional column in a database - it is easy to make a trait for it to make it reusable
But
2. To not have any additional code in each repository, how to accomplish the logic of "if column is tru, prevent delete" with help of Annotation? Like it is in SoftDeletable example above.
Thank you in advance.
You could do this down at the database level. Just create a table called for example protected_users with foreign key to users and set the key to ON DELETE RESTRICT. Create a record in this table for every user you don't want to delete. That way any attempt to delete the record will fail both in Doctrine as well as on db level (on any manual intervention in db). No edit to users entity itself is needed and it's protected even without Doctrine. Of course, you can make an entity for that protected_users table.
You can also create a method on User entity like isProtected() which will just check if related ProtectedUser entity exists.
You should have a look at the doctrine events with Symfony:
Step1: I create a ProtectedInterface interface with one method:
public function isDeletable(): boolean
Step2: I create a ProtectionTrait trait which create a new property. This isDeletable property is annotated with #ORM/Column. The trait implements the isDeletable(). It only is a getter.
If my entity could have some undeletable data, I update the class. My class will now implement my DeleteProtectedInterface and use my ProtectionTrait.
Step3: I create an exception which will be thrown each time someone try to delete an undeletable entity.
Step4: Here is the tips: I create a listener like the softdeletable. In this listener, I add a condition test when my entity implements the ProtectedInterface, I call the getter isDeleteable():
final class ProtectedDeletableSubscriber implements EventSubscriber
{
public function onFlush(OnFlushEventArgs $onFlushEventArgs): void
{
$entityManager = $onFlushEventArgs->getEntityManager();
$unitOfWork = $entityManager->getUnitOfWork();
foreach ($unitOfWork->getScheduledEntityDeletions() as $entity) {
if ($entity instanceof ProtectedInterface && !$entity->isDeletable()) {
throw new EntityNotDeletableException();
}
}
}
}
I think that this code could be optimized, because it is called each time I delete an entity. On my application, users don't delete a lot of data. If you use the SoftDeletable component, you should replace it by a mix between this one and the original one to avoid a lot of test. As example, you could do this:
final class ProtectedSoftDeletableSubscriber implements EventSubscriber
{
public function onFlush(OnFlushEventArgs $onFlushEventArgs): void
{
$entityManager = $onFlushEventArgs->getEntityManager();
$unitOfWork = $entityManager->getUnitOfWork();
foreach ($unitOfWork->getScheduledEntityDeletions() as $entity) {
if ($entity instanceof ProtectedInterface && !$entity->isDeletable()) {
throw new EntityNotDeletableException();
}
if (!$entity instance SoftDeletableInterface) {
return
}
//paste the code of the softdeletable subscriber
}
}
}
Well the best way to achieve this is to have one more column in the database for example boolean canBeDeleted and set it to true if the record must not be deleted. Then in the delete method in your repository you can check if the record that is passed to be deleted can be deleted and throw exception or handle the situation by other way. You can add this field to a trait and add it to any entity with just one line.
Soft delete is when you want to mark a record as deleted but you want it to stay in the database.

Laravel: Create or update related model?

Please be gentle with me - I'm a Laravel noob.
So currently, I loop through a load of users deciding whether I need to update a related model (UserLocation).
I've got as far as creating a UserLocation if it needs creating, and after a bit of fumbling, I've come up with the following;
$coords = $json->features[0]->geometry->coordinates;
$location = new UserLocation(['lat'=>$coords[1],'lng'=>$coords[0]]);
$user->location()->save($location);
My issue is that one the second time around, the Location may want updating and a row will already exist for that user.
Is this handled automatically, or do I need to do something different?
The code reads like it's creating a new row, so wouldn't handle the case of needing to update it?
Update - solution:
Thanks to Matthew, I've come up with the following solution;
$location = UserLocation::firstOrNew(['user_id'=>$user->id]);
$location->user_id = $user->id;
$location->lat = $coords[1];
$location->lng = $coords[0];
$location->save();
You should reference the Laravel API Docs. I don't think they mention these methods in the "regular docs" though so I understand why you may have not seen it.
You can use the models firstOrNew or firstOrCreate methods.
firstOrNew: Get the first record matching the attributes or instantiate
it.
firstOrCreate: Get the first record matching the attributes or create it.
For Example:
$model = SomeModel::firstOrNew(['model_id' => 4]);
In the above example, if a model with a model_id of 4 isn't found then it creates a new instance of SomeModel. Which you can then manipulate and later ->save(). If it is found, it is returned.
You can also use firstOrCreate, which instead of creating a new Model instance would insert the new model into the table immediately.
So in your instance:
$location = UserLocation::firstOrNew(['lat'=>$coords[1],'lng'=>$coords[0]]);
$location will either contain the existing model from the DB or a new instance with the attributes lat and lng set to $coords[1] and $coords[0] respectively, which you can then save or set more attribute values if needed.
Another example:
$location = UserLocation::firstOrCreate(['lat'=>$coords[1],'lng'=>$coords[0]]);
$location will either contain the existing model from the DB or a new model with the attributes set again, except this time the model will have already been written to the table if not found.

Silverstripe 3.1 - Can't create a new many_many relation

while extending the CsvBulkUploader to fit my needs, I cam across the problem, that Silverstripe doesn't let me create a new entry for a many_many relation.
My dataobject is ShopItems and has a many_many relation called Visuals. So in my MySQL database I get ShopItems_Visuals.
Now I want to create a new entry for this with the following code, and I think here's the place I made some mistake.
...
$visual = ShopItem_Visuals::create();
$visual->ImageID = $file->ID;
$visual->ShopItemID = $obj->ID;
$visual->write();
...
after adding this to my function, I receive Class 'ShopItem_Visuals' not found after hitting the import button.
Is that because the database Table was created through the many_many relation in ShopItem and has no ClassName itself?
Can someone tell me how to create a new entry for this relation?
Thank you in advance.
I don't think that there's a Class for the mapping table itself.
The entry in it should be created automagically, when adding a related Object via add.
$visual = new Visual();
...
$visual->write();
$ShoptItem->Visuals()->add($visual);
$ShoptItem->write();
If the many-many-relation name is Visuals, calling ->Visuals() should return an instance of ManyManyList on which you can call add, remove etc.
see http://api.silverstripe.org/3.0/class-ManyManyList.html

Kohana ORM Update not working

I have discovered Kohana just 2 days ago and, after facing a few problems and managing to deal with them, I ran into a quite strange one.
When I try to update an entry in DB, instead of updating the entry ORM just inserts a new row.
Everything is similar to this example http://kohanaframework.org/3.0/guide/orm/examples/simple
My code (controller file):
class Controller_Admin extends Controller {
...
public function action_test($id)
{
$inquiry = ORM::factory('inquiry')->where('Id', '=', $id)->find(); // $inquiry = Model_Inquiry($id) doesn't work, too
$inquiry ->Name = 'Someone';
$inquiry ->save();
}
...
}
Model file:
class Model_Inquiry extends ORM
{
protected $_table_name = 'mytable';
}
Do you have any ideas why it's inserting a new entry instead of updating the old one? I read that it's because the ID is not correctly set, but I tried using a fixed value (->where('Id', '=', 5)) and it didn't work (it still inserted a new row).
Thanks in advance!
Your record isn't loaded in the first place. To check if it's loaded, do:
if ($inquiry->loaded()){...
Also, you can check what query has been run by doing:
echo $inquiry->last_query();
So you can manually check what exactly is being returned to ORM.
The main problem here is that you're using save() instead of being more strict and using create() / update(). If you used update(), ORM would throw an exception complaining about the record not being loaded.
Save is basically a proxy to these methods, relying on the loaded state.
(I assume that you're using Kohana 3.1 since 3.0 ORM doesn't have separate update / create methods at all)

Categories