Symfony2 Doctrine2 native queries basics - symfony

I am developing a basic web-app in my job. I have to work with some sql server views. I made the decision of trying native queries, and once tested it's functionality, try to write some classes to code all the queries and kinda forget their implementation.
So my issue is, I've got an Entity in Acme/MyBundle/Entity/View1.php.
This entity has got all the attributes matching the table and also it's getters and setters.
I guess this entity is well mapped to the DB (Doctrine cant work with views easily).
My aim is to let a Controller be able to fetch some data from those views(SQL SERVER) and return it to the view (twig) so it can display the info.
$returned_atts = array(
"att1" => $result[0]->getAttribute1(), //getter from the entity
"att2" => $result[1]->getAttribute2(), //getter from the entity
);
return $returned_atts;`$sql = "SELECT [Attribute1],[Attribute2],[Attribute3] FROM [TEST].[dbo].[TEST_VIEW1]"; //THIS IS THE SQL SERVER QUERY
$rsm = new ResultSetMapping($em); //result set mappin object
$rsm->addEntityResult('Acme\MyBundle\Entity\View1', 'view1'); //entity which is based on
$rsm->addFieldResult('view1', 'Attribute1', 'attribute1'); //only choose these 3 attributes among the whole available
$rsm->addFieldResult('view1', 'Attribute2', 'attribute2');
$rsm->addFieldResult('view1', 'Attribute3', 'attribute3');
//rsm built
$query = $em->createNativeQuery($sql, $rsm); //execute the query
$result = $query->getResult(); //get the array
It should be possible to return the array straight from the getResult() method isn't it?
And what's killing me, how can I access the attribute1, attriute2 and attriute2?
$returned_atts = array(
"att1" => $result[0]->getAttribute1(), //getter from the entity
"att2" => $result[1]->getAttribute2(), //getter from the entity
);
return $returned_atts;`

If you want result as array, you don't need to use ResultSetMapping.
$sql = " SELECT * FROM some_table";
$stmt = $this->getDoctrine()->getEntityManager()->getConnection()->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
That is a basic example for controller action. You can dump the result, use var_dump(), to see how to access your particular field values.
More examples here Doctrine raw sql

Related

How to manually set a property in Sonata Admin ListMapper from database

My model has a "parent" entity called Application and a "child" entity called "role" which joins to application via a ManyToOne relationship.
However, Application does not have an inverse "oneToMany" relationship to Role for performance reasons.
What I'm trying to do is to join a role entity to the application entity on the Application's Sonata Admin List.
The closest I've been able to come is using createQuery on the applicationAdmin class like so:
public function createQuery($context = 'list'){
$query = parent::createQuery($context);
$query
->leftJoin('fnBundle:Role','r','WITH','r.application = ' . $query->getRootAlias() . '.id')
->leftJoin('fnBundle:User','u','WITH','ar.user = u')
->addSelect('u.email');
return $query;
}
This dies with the following error:
"Warning: get_class() expects parameter 1 to be object, array given")
in "SonataAdminBundle:CRUD:base_list_field.html.twig"
I believe (though I've had trouble proving) this is because the return application object is nested in an array with two keys like
array(0 => <Application Object>, 1 => <User Email>);
instead of just the application object.
So how would I go about fixing this? Can I select the u.email AS a property of the application (I don't think so, I've been looking for a solution)...should I override the DataGrid somehow, or is there no elegant solution to this problem?
Thanks!

Symfony2 Doctrine Join Entity

I have a entity with the next join:
class blogComment
{
....
/**
* #ORM\OneToMany(targetEntity="BlogComment", mappedBy="replyTo")
*/
protected $replies;
....
}
Now I get successfully all the replies. But I only want to get: where active = true
How to do that?
Oke if you guys recommend to get the comments by query in the controller how to build a nested array to get result like this:
For solving the part where you only want active replies there are a couple of options:
1) Use some custom DQL in a repository:
$dql = 'SELECT bc FROM BlogComment bc WHERE bc.replyTo = :id AND bc.active = :active';
$q = $em->createQuery($dql)
->setParameters(array('id' => $id, 'active' => true));
2) Using ArrayCollection::filter() in the getter:
public function getReplies()
{
return $this->replies
->filter(function ($reply) {
return $reply->isActive();
})
->toArray();
}
3) Using ArrayCollection::matching() (Collection Criteria API) in the getter:
use Doctrine\Common\Collections\Criteria;
// ...
public function getReplies()
{
$criteria = new Criteria::create()
->where(Criteria::expr()->eq('active', true));
return $this->replies
->matching($criteria)
->toArray();
}
4) Use Filters. These can add where clauses to queries regardless of where that query is generated. Please see the docs.
If you want to be able to fetch an entire set of replies, nested and all, in a single query, you need to implement some kind of "tree" of "nested set" functionality. I'd advise you to look at the Tree behavior of l3pp4rd/DoctrineExtensions.
http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html
Wherever you are obtaining your blog comments to display them (probably on a controller), you need to customise your query so that only the active replies are extracted. Something like:
$query = $em->createQuery('SELECT b FROM blogComment b JOIN b.replies r WHERE r.active = :active');
$query->setParameter('active', true);
$blogComments = $query->getResult();
EDIT:
For your new requirement of nested replies, you would need to specify a relationship between a comment entity and its parent comment.

Symfony2 (doctrine2) native sql insert

How to insert data in symfony2 doctrine2 on native sql?
My query
insert into propriedades (id,name,descripcion,num_lote,cod_imovel,imovel,convenio,proprietar,cpf,area_ha,perimetro,location,centro) VALUES (nextval('propriedades_id_seq'),'?','?','?','?','?','?','?','?','?','?',ST_GeomFromKML('<Polygon><outerBoundaryIs><LinearRing><coordinates>".$terra['coordinates']."</coordinates></LinearRing></outerBoundaryIs></Polygon>'),ST_Centroid(ST_GeomFromKML('<Polygon><outerBoundaryIs><LinearRing><coordinates>".$terra['coordinates']."</coordinates></LinearRing></outerBoundaryIs></Polygon>')))
You have to use $conn->insert('table', $dataArray);. See documentation
In 2020 you can do something like (example query, adapt it to your params):
$query = "
INSERT INTO `user_challenges_claimed`
SET
`season_id` = :seasonId,
`user_id` = :userId,
`interval_type` = :intervalType,
`is_claimed` = true
ON DUPLICATE KEY UPDATE
`is_claimed` = true
;
";
// set query params
$queryParams = [
'seasonId' => $seasonId,
'userId' => $userId,
'intervalType' => $intervalType,
];
// execure query and get result
$result = $this->manager->getConnection()
->executeQuery(
$query,
$queryParams
);
// clear manager entities
$this->manager->clear();
// optional - assert row has been inserted/modified
if ($result->rowCount() < 1) {
throw new ChallengeAlreadyClaimedException(
"[{$seasonId}:{$userId} - {$intervalType}]"
);
}
$this->manager is an object implementing EntityManagerInterface (ie EntityManager).
Usually you do not use what you call native sql in a symfony 2 project but the high level Doctrine ORM layer.
However there is a doctrine dbal layer which enables e.g. mysql queries instead of DQL. Here is the reference
http://symfony.com/doc/2.0/cookbook/doctrine/dbal.html

How to update a Doctrine Entity from a serialized JSON?

We are using Symfony2 to create an API. When updating a record, we expect the JSON input to represent a serialized updated entity. The JSON data will not contain some fields (for instance, CreatedAt should be set only once when the entity is created - and never updated). For instance, here is an example JSON PUT request:
{"id":"1","name":"anyname","description":"anydescription"}
Here is the PHP code on the Controller that should update the entity according to the JSON above (we are using JMS serializer Bundle):
$supplier = $serializer->deserialize(
$this->get('request')->getContent(),
'WhateverEntity',
'json'
);
The EntityManger understands (correctly) that this is an update request (in fact, a SELECT query is implicitly triggered). The EntityManager also guess (not correctly) that CreatedAt property should be NULLified - it should instead keep the previous one.
How to fix this issue?
It's possible as well to do it with Symfony Serializer using object_to_populate option.
Example: I receive JSON request. If record exists in database I want to update fields received in body, if it does not exist I want to create new one.
/**
* #Route("/{id}", methods={"PUT"})
*/
public function upsert(string $id, Request $request, SerializerInterface $serializer)
{
$content = $request->getContent(); // Get json from request
$product = $this->getDoctrine()->getRepository(Product::class)->findOne($id); // Try to find product in database with provided id
if (!$product) { // If product does not exist, create fresh entity
$product = new Product();
}
$product = $serializer->deserialize(
$content,
Product::class,
'json',
['object_to_populate' => $product] // Populate deserialized JSON content into existing/new entity
);
// validation, etc...
$this->getDoctrine()->getManager()->persist($product); // Will produce update/instert statement
$this->getDoctrine()->getManager()->flush($product);
// (...)
using the JMSSerializerBundle follow the install instructions at
http://jmsyst.com/bundles/JMSSerializerBundle
either create your own serializer service or alter the JMSSerializerBundle to use the doctrine object constructor instead of the simple object constructor.
<service id="jms_serializer.object_constructor" alias="jms_serializer.doctrine_object_constructor" public="false"/>
This basically handles exactly what Ocramius solution does but using the JMSSerializerBundles deserialize.
I would use the Doctrine\ORM\Mapping\ClassMetadata API to discover existing fields in your entity.
You can do following (I don't know how JMSSerializerBundle works):
//Unserialize data into $data
$metadata = $em->getMetadataFactory()->getMetadataFor($FQCN);
$id = array();
foreach ($metadata->getIdentifierFieldNames() as $identifier) {
if (!isset($data[$identifier])) {
throw new InvalidArgumentException('Missing identifier');
}
$id[$identifier] = $data[$identifier];
unset($data[$identifier]);
}
$entity = $em->find($metadata->getName(), $id);
foreach ($metadata->getFieldNames() as $field) {
//add necessary checks about field read/write operation feasibility here
if (isset($data[$field])) {
//careful! setters are not being called! Inflection is up to you if you need it!
$metadata->setFieldValue($entity, $field, $data[$field]);
}
}
$em->flush();

How to list user based on their roles in Symfony2 + Doctrine effectively

I have done this with this code
$users = $this->getDoctrine()->getEntityManager()
->createQuery('SELECT tu FROM UserBundle:User tu')
->getResult();
$result = array();
foreach($users as $user){
if($user->hasRole('ROLE_CUSTOMER'))
$result[] = $user;
}
return $this->render('XBundle:Order:index.html.twig',
array('users' => $result));
But what is the simple way to achieve this same result ?
Thanks.
Update, additional info:
Our main problem is that user roles have a hierarchical structure.
So ROLE_EDITOR will automatically have ROLE_WRITER if I defined ROLE_WRITER under ROLE_EDITOR.
Thus I can't just use simple query, I think I also have to utilize security context component.
I don't know your schema, but I guess you could do an INNER JOIN and put your condition in the ON clause. Read this article about the query builder to figure out how to build your query.
Doctrine collections also have a filter method that takes a Closure as an argument.

Resources