Symfony 3- select query - symfony

I'm new to symfony and I'm having a hard time developing a query ... thanks if anyone could help me
What I need is
select id and code from table where id = userid and code = usercode
if the values ​​are equal if statement to insert data into the database, otherwise error message
i try this
$teste = $this->getDoctrine()->getRepository('AppBundle:Codigo');
$query = $teste->createQueryBuilder('p')
->where('p.codigo = :codigo')
->andWhere('p.utilizadorID = :user')
->setParameter('codigo', $codigo)
->setParameter('user', $user)
->getQuery();
}
$cod = $query->getResult();
if ( $cod <> NULL) {
$link = $data['linkpodcast'];
$podcast->setUrl($link);
$podcast->setIdUser($user);
$sn = $this->getDoctrine()->getManager();
$sn -> persist($podcast);
$sn -> flush();
$this->addFlash(
'notice',
'Podcast Adicionado'
);
return $this->redirectToRoute('gravar_list');
}

Related

Perl make a SELECT query and return array of objects

I want to make a query to a sqlite database and return an array of objects.
I'm creating a telegram bot and i have to store the date of last message per user_id, because telegram API returns messages i've already read. So i've created a sqlite db with two tables: users and messages; users contains all the user_id and username; messages contains the last message_id i've read.
I've done this function, it works but it isn't performing very well because it has to recreate the entire array of objects (fetchrow_hashref).
sub sqlLiteSelect {
my ($db,$table,$columnsRef,$where,$others) = #_;
my $columns = join(', ', #{ $columnsRef });
$others ||= '';
my $query = "select ${columns} from ${table} ${where}${others}";
my $obj = $db->prepare($query);
my $ret = $obj->execute() or die $DBI::errstr;
my #array = ();
while(my $row = $obj->fetchrow_hashref) {
my $tmp = {};
foreach my $column (#{ $columnsRef }) {
$tmp->{$column} = $row->{$column};
}
push #array, $tmp;
}
return #array;
}
my #columns = ('user_id','first_name','username','type');
my $where = ' where user_id in (1,2)';
my #result = sqlLiteSelect($db,'users',\#columns,$where,'');
foreach my $row (#result) {
print "user_id=$row->{user_id}, username=$row->{username}\n";
}
I expect my select to return an array of object without recreate it everytime.
my ($user_id, $first_name, $username, $type);
my $sql = q{
SELECT user_id, first_name, username, type
FROM users
WHERE user_id IN (1,2)
};
my $sth = $db->prepare($sql);
$sth->execute or die $DBI::errstr;
$sth->bind_columns(\$user_id, \$first_name, \$username, \$type);
while ($sth->fetch) {
print "$user_id, $username\n";
}
read the documentation https://metacpan.org/pod/DBI#bind_columns

doctrine pagination with join statement

I am trying to right a query which return me list of the users which has uploaded video(user_id in video table ), and have paginating thingy in the query
the function is like this :
public function getUsersHasVideoShoutOut($offset, $limit)
{
$qb = $this->createQueryBuilder('u')
->Join('u.video', 'uv');
$qb->where('uv.muted=0')
->andwhere('u.muted = 0')
->addOrderBy('uv.release_date', 'DESC')
->setFirstResult($offset)
->setMaxResults($limit);
return $qb->getQuery()->getResult();
}
but the problem is that I get duplicate data in next pages , is it because of join statement and pagination in doctorine ?
You can get distinct data:
public function getUsersHasVideoShoutOut($offset, $limit)
{
$qb = $this->createQueryBuilder('u')
->Join('u.video', 'uv');
$qb->where('uv.muted=0')
->andwhere('u.muted = 0')
->addOrderBy('uv.release_date', 'DESC')
->setFirstResult($offset)
->setMaxResults($limit)
->distinct();
return $qb->getQuery()->getResult();
}

Error: Invalid PathExpression. Must be a StateFieldPathExpression.

I'm working on a symfony project entity with query builder. When I try to run this function I get this issue.
[Semantical Error] line 0, col 9 near 'category FROM': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
public function json_filterAllproductsAction() {
$search = "";
$category = 1;
//Combine tables and create the query with querybuilder
$em = $this->container->get('doctrine.orm.entity_manager');
$qb = $em->createQueryBuilder();
$qb->select('p.category')
->from('EagleAdminBundle:Products', 'p')
->orderBy('p.id', 'DESC');
if ($category != 0) {
$qb->andWhere('p.category = :category')
->setParameter('category', $category);
}
$qb->andWhere('p.productTitle LIKE :title')
->setParameter('title', "$search%");
//convert to json using "JMSSerializerBundle"
$serializer = $this->container->get('serializer');
$jsonproducts = $serializer->serialize($qb->getQuery()->getResult(), 'json');
return new Response($jsonproducts);
}
I think error is in,
$qb->select('p.category')
It would be great help someone can help me.
You need to fetch category as well in your join. Something like this should work fine:
$qb->select('p', 'c')
->from('EagleAdminBundle:Products', 'p')
->orderBy('p.id', 'DESC')
->join('p.category', 'c');
if ($category != 0) {
$qb->andWhere('p.category = :category')
->setParameter('category', $category);
}
$qb->andWhere('p.productTitle LIKE :title')
->setParameter('title', "$search%");
Note if you don't want to limit your search to only products that have categories you can change the join to a leftJoin.
Also note you can have the serializer configured to serialize the category property of product. Then you should just be able to fetch a product and have it automatically serialize the category for you.

Doctrine and Like query symfony2

I have a search bar in my page and the action in my in charge of looking for what the user search for is this :
public function searchAction(Request $request){
$em = $this->container->get('doctrine')->getEntityManager();
$evenements= $em->getRepository('Mql14mqlmeBundle:Evenement')->findAll();
if ('POST' === $request->getMethod()) {
$search = $request->get('search');
$query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :search')
->setParameter('search', $search);
$resultats = $query->getResult();
return $this->container->get('templating')->renderResponse('Mql14mqlmeBundle:Event:search.html.twig', array(
'resultats'=>$resultats,
));
}
return $this->listerAction();
}
It's working if the user put the exact name of some event in the database, but I want to make the search possible even if it's only a part of the name, I tried this in the query:
$query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :%search%')
->setParameter('search', $search);
But I'm getting this error: Invalid parameter format, : given, but :name or ?num expected.
Try to change parameter like this:
$query = $this
->container
->get('doctrine')
->getEntityManager()
->createQuery(
'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :search'
)
->setParameter('search', '%'.$search.'%');

Symfony2 / Typecasting query results to simpeler object

I am using Stof's DoctrineExtension bundle to retrieve my Tree, now I want to convert that tree to an array (which will then in turn get converted to json).
The format of NestedTreeRepository->childrenHierarchy() is not in the correct format though, I want to modify the output so only the node "title" property and the "id" property is returned, and put any children in a "children" subarray. In compliance with this format (JSON):
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
}
I have tried to following code, this returns the same as childrenHierarchy() but would allow me to modify the query.
$query = $em
->createQueryBuilder()
->select('node')
->from('MyBundle:Page', 'node')
->orderBy('node.root, node.lft', 'ASC')
->getQuery()
;
$nodes = $query->getArrayResult();
[Do magic here]
$tree = $pagerepo->buildTree($nodes);
Is it possible to typecast every node into a much simpler object containing only the following property's:
id
title
a few other ints used for positioning
if I would then run that through json_encode() I would have exactly what I needed.
Any other solutions are of course welcome.
my code for this purpose (just made this a few hours ago)
it's a remake of stof's buildTreeArray function
in the controller (I'm writing this for symfony2):
function gettreeAction {
$query = .... // do your query
$tree = $this->buildTree($query->getArrayResult());
$response = new Response(json_encode($tree));
return $response;
}
private function buildTree($nodes)
{
$nestedTree = array();
$l = 0;
if (count($nodes) > 0) {
// Node Stack. Used to help building the hierarchy
$stack = array();
foreach ($nodes as $child) {
$item = array();
$item['name'] = $child['title'];
$item['id'] = 'page_'.$child['id'];
$item['level'] = $child['level'];
$item['children'] = array();
// Number of stack items
$l = count($stack);
// Check if we're dealing with different levels
while($l > 0 && $stack[$l - 1]['level'] >= $item['level']) {
array_pop($stack);
$l--;
}
// Stack is empty (we are inspecting the root)
if ($l == 0) {
// Assigning the root child
$i = count($nestedTree);
$nestedTree[$i] = $item;
$stack[] = &$nestedTree[$i];
} else {
// Add child to parent
$i = count($stack[$l - 1]['children']);
$stack[$l - 1]['children'][$i] = $item;
$stack[] = &$stack[$l - 1]['children'][$i];
}
}
}
return $nestedTree;
}
works perfectly with jqTree...
I have solved it as following:
public function getPageTreeAction() {
$pagerepo = $this->getDoctrine()->getRepository('MyBundle:Page');
$em = $this->getDoctrine()->getEntityManager();
$query = $em
->createQueryBuilder()
->select('node')
->from('MyCorpBundle:Page', 'node')
->orderBy('node.root, node.lft', 'ASC')
->getQuery();
$flatnodearray = $query->getArrayResult();
$flatsimplenodearray = array();
foreach ($flatnodearray as $currentNode) {
$currentSimpleNode = array();
$currentSimpleNode['id'] = $currentNode['id'];
$currentSimpleNode['lft'] =$currentNode['lft'];
$currentSimpleNode['rgt'] = $currentNode['rgt'];
$currentSimpleNode['lvl'] = $currentNode['lvl'];
$currentSimpleNode['title'] = $currentNode['title'];
$flatsimplenodearray[] = $currentSimpleNode;
}
$tree = $pagerepo->buildTree($flatsimplenodearray);
$response = new Response(json_encode($tree));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
I would use the Stofs Repository function to get the nodes in an hierarchical array:
$repo = $em->getRepository('MyBundle:Page');
$arrayTree = $repo->childrenHierarchy();
And I think there is no other solution than modify that array manually. After you have removed some properties that you dont need, you can json_encode the array and return it.

Resources