I want add a new column with uniquie=true but every time get duplicate values '' , this column i want to be not null. How can i construct a migration to do that, i was try many ways but i read only if have my update query in function up this query will be loaded. but in function postUp i set my unique fields vales.
This i was trying but not working:
public function postUp(Schema $schema){
$users = $this->container->get('doctrine')->getRepository('AppBundle:Users')->findAll();
foreach($users as $user){
$user->setAffiliatesToken(uniqid().str_replace(' ','',str_replace('.','',microtime())));
}
$this->addSql('CREATE UNIQUE INDEX UNIQ_1483A5E952C22EB5 ON users (affiliates_token)');
$this->addSql('CREATE INDEX IDX_1483A5E99F12C49A ON users (affiliate_id)');
$this->container->get('doctrine')->getManager()->flush();
}
Related
I want to insert a value having already defined id in the table which have auto increment column id(PK) in doctrine symfony.
You can change the ID generator temporarily to store given primary ids like:
use App\Entity\YourEntity;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AssignedGenerator;
use Doctrine\ORM\Mapping\ClassMetadata;
$entity = new YourEntity();
$entity->setId(101);
$entity->setSomething('foo');
$entityManager->persist($entity);
// change the ID generator temporarily before flushing
$metadata = $entityManager->getClassMetaData(YourEntity::class);
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new AssignedGenerator());
$entityManager->flush();
Note : generally you should not update the id of an existing row in the dataBase.
But However.. Assuming that your entity look like has fields : ID and nameValue :
$car = $carsRepository->find(10); // select a car which the id is 10
$car->setId(1025); // note that : by default your entity DOES NOT have a built method setID() so you have to write it.
$car->setNameValue("Opel");
$manager->flush();
I have a User table and a Library table, the relationship between them are many to many.
So I have a user_library table.
I manage to add data to the Library table from User but I cannot recover the data afterwards.
I add them like this:
$em = $this->getDoctrine()->getManager();
$repoUser = $em->getRepository('App:User');
$user = $repoUser->findOneBy(['token' => $token_user]);
$library = new Library();
$library->setIdBook($id_book);
$user->addLibrary($library);
$em->persist($library);
$em->persist($user);
$em->flush();
I thought that simply doing: $user->getLibrary()->getIdBook() would be enough but it is not the case.
How do you think I can get all the id_book that match the user?
The thing is that your getLibrary returns ArrayCollection, you need to specify which Library you exactly want
$libararies = $user->getLibrary() // <- this returns ArrayCollection
$library = $libraries->first() // <- return 1st element
Based on this code you can do a search for example, or just use doctrine to fetch library with desired ID, user, whatever you need straight from the database
EDIT
Lets say you want all libraries that are in relation with user with ID = 4
... // your code
$user = $this->getDoctrine()->getRepository('your user class')->find(4); // here we find your user from DB
$libraries = $user->getLibrary() // here we get all libraries which are in relation with user #4, you might want to rename the function as it returns ArrayCollection of Libraries, not Library
$bookIds = array();
foreach($libraries as $library) {
$bookIds[] = $library->getIdBook();
}
dump($bookIds); // all user #4 book ids
die;
I need to create a new set of DB records by using same data that already exists. See image below:
Using this as example I need to create the same set of records but just changing the column company, less take UPC = I5TYF1UPORMYUY4JT21Z, using this info I should be able to generate two rows by just changing the company to 52 (any number). What I think is to get those records using this:
$entityStockDetailHasProductDetail = $this->getDoctrine()->getManager()->getRepository('ProductBundle:StockDetailHasProductDetail')->findBy(array(
"product" => $request->request->get('product')['id'],
"upc" => $request->request->get('product')['upc'],
));
Which returns the right records but I don't know how to continue from that point. My entity has all this methods:
$entityStockDetailHasProductDetail->setProductDetail();
$entityStockDetailHasProductDetail->setUpc();
$entityStockDetailHasProductDetail->setProduct();
$entityStockDetailHasProductDetail->setCompany();
$entityStockDetailHasProductDetail->setCondition();
$entityStockDetailHasProductDetail->setContent();
Any ideas?
Just loop over the collection, clone your entities, set the new company and persist.
$em = $this->getDoctrine()->getEntityManager('default');
$collection = $em->getRepository('YourBundle:Entity')->findBy(array('...'));
foreach ($collection as $entity) {
$newEntity = clone $entity;
$newEntity
->setId(null)
->setCompany($company)
;
$em->persist($newEntity);
}
$em->flush();
i have function
private function updateCharacters($oApiKeyInfo) // argument is base entity
{
$aXmlCharacter = $this->fXml->getXmlRowset($this->oXml, 'row');
// insert new
foreach ($aXmlCharacter as $oXmlCharacter)
{
$loopData = $this->fXml->getXmlAttributesAsArray($oXmlCharacter);
$oApiKeyInfoCharacters = new apiKeyInfoCharacters();
$oApiKeyInfoCharacters
->setKeyID($this->keyID)
->setCharacterID($loopData['characterID'])
->setCharacterName($loopData['characterName'])
->setCorporationID($loopData['corporationID'])
->setCorporationName($loopData['corporationName'])
->set_apiKeyInfo_byKeyID($oApiKeyInfo);
$this->em->persist($oApiKeyInfoCharacters);
}
// $this->em->flush() is in main (public) function
}
but, it creates dublicates... and i want that in db was ONLY that entries that is in $aXmlCharacter (array), others must be deleted
now code above is only adding new entries, but i need remove previous
can someone help to deal with it? and please show working examples
Dublicate entries i can not see any definition for uniquenes.
Deleting an Object vom database is simple as the documentation shows.
$product = $em->getRepository('YourBundle::apiKeyInfoCharacters')->find($id);
$em->remove($product);
$em->flush();
But why do you want to delete the existing one instead of updating?
I have table called
tasks---id ,name,groupid
user----id,username , groupid
Now i have another table
userTasks with fields id,name, taskid , userid
Now i want that when the new user is created or persisted in database then
all the tasks with same groupid asuser should gets inserted in
usertasks table with taskid and userid
HOw can i do that
I am thinking of puting the logic in postFlush() event
But i don't know how doctrine first select and then insert the records in that table
If your do it just after of insert the data, instead inside postFlush function, could be more confortable and easy.
$om->persist($user);
$om->persist($task);
$om->flush();
$usertask = new UserTask($id, $name, $user->getId(), $task->getId());
$om->flush();
$om is the ObjectManager; EntityManager is deprecated in Doctrine last version.
If you want to use postFlush() function, maybe have to declare both id's as private variables to have the info.