Drupal 8: convert node id from string to integer - drupal

Retrieve a node based on condition:
$query = \Drupal::entityQuery('node')
->condition('type', 'my_content_type')
->condition('title', 'my node title');
$nid = $query->execute();
The result of $nid is the correct node ID but the format is a string, (es: "123")
When I want to load the node by its ID, I write:
$node_id = Node::load($nid);
Doing this, the result I get is NULL because the variable $nid is holding a string (not integer).
If I write the code like this:
$node_id = Node::load(123);
I get the node loaded.
How can I convert the variable string ($nid) as an integer ?
I tried:
$nid_int = (int) $nid;
$node_id = Node::load($nid_int);
also I tried:
$nid_int = intval($nid);
$node_id = Node::load($nid_int);
But I alwas get result NULL
Thanks for your help

You can't use Node::load($nid); directly, because the $query->execute() return an array like ['vid' => "nid"].
$query = \Drupal::entityQuery('node')
->condition('type', 'my_content_type')
->condition('title', 'my node title');
$nids = $query->execute();
$nid = (int)array_shift($nids);

Can try:-
$nid_string = $nid->__toString();
$node_id = Node::load((int) $nid_string);

Related

Doctrine select with subselect returning hydrated object

I want to do a query like:
$qbFoo = $this->createQueryBuilder('foo');
$qbFoo->where($qbFoo->expr()-eq('foo.field', $value));
$qbProduct = $this->createQueryBuilder('product');
$qbProduct->select(['product'])
->addSelect(sprintf('(%s) as foo', $qbFoo->getDQL()))
->where($qbProduct->expr()->eq('product.id', $prodId));
$result = $qbProduct->getQuery()->getResult();
The value of $result will be:
$result[0][0] = {AppBundle\Entity\Product}
$result[0]['foo'] = 6 (6 is the value of foo.id)
How can I get the $result to be like:
$result[0][0] = {AppBundle\Entity\Product}
$result[0]['foo'] = {AppBundle\Entity\Foo}

How to use notanyof in nlobjSearchFilter

var ids = ['1', '2', '3'];
var filters = new Array();
filters[0] = new nlobjSearchFilter('mainline', null, 'is', 'T');
filters[4] = new nlobjSearchFilter('entity', null, 'notanyof', ids);
var searchResult = nlapiSearchRecord('creditmemo', null, filters, columns);
Hello I'm trying to list all credit memos but where the customer ID is not 1,2 or 3?
Can you help me? Thanks
The proper operator is "noneof".
new nlobjSearchFilter('entity',null,'noneof',[1,2,3]);

Update randomly certain number of rows

I'm trying to update a certain number of rows of my entity "Vehicule". I have no idea how could it work.
I'm actually trying to modify only two rows where direction= 5.This is the function I used in order to update.
public function ValidAction(\OC\UserBundle\Entity\User $direction) {
$qb = $this->getDoctrine()
->getRepository('CarPfeBundle:Vehicule')
->createQueryBuilder('v');
$q = $qb->update ('CarPfeBundle:vehicule v')
->set('v.direction', '?1')
->where('v.direction = ?2')
->setParameter(1, $direction)
->setParameter(2, 5)
->getQuery();
$p = $q->execute();
return $this->redirect($this->generateUrl('demandeveh_afficher'));
}
But the above code update all rows of my database. I need to update only two rows. Any help please?
Try to do this ;
public function ValidAction(\OC\UserBundle\Entity\User $direction) {
$qb = $this->getDoctrine()
->getRepository('CarPfeBundle:Vehicule')
->createQueryBuilder('v');
// $ids an array that contains all ids with your condition
$ids = $qb->select('v.id')
->where('v.direction = :direction')
->setParameter(
array(
'direction' => $direction
)
)
->getQuery()
->getResult();
$id1 = $ids[array_rand($ids)];
$id2 = $ids[array_rand($ids)];
//To be sure that $id1 is different from id2
while ($id1 == $id2) {
$id2 = $ids[array_rand($ids)];
}
$q = $qb->update ('CarPfeBundle:vehicule v')
->set('v.direction', ':val1')
->where('v.direction = :val2')
->andWhere('v.id IN (:id1, :id2)')
->setParameter(
array(
'val1' => $direction ,
'val2' => 5 ,
'id1' => $id1,
'id2' => $id2,
)
)
->getQuery();
$p = $q->execute();
return $this->redirect($this->generateUrl('demandeveh_afficher'));
}
With the above code I hope you can update only two rows and randomly.
Good luck !
While a solution like Houssem Zitoun suggested may work, why not use a subquery?
If you get the (like I did, if not, just skip the middle SELECT)
Error: #1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
go with this answer and something like (doc): - untested
UPDATE CarPfeBundle:Vehicule v
SET v.direction = ?1
WHERE v.direction IN
(SELECT * FROM (
SELECT v.direction
FROM CarPfeBundle:Vehicule v2
WHERE v.direction = ?2 LIMIT 2
)) AS sq

doctrine dql exception: Illegal offset type in /var/www/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php line 601

I want to produce a DQL for following MySQL query:
SELECT * FROM `folders` AS `t` WHERE `t`.`Library` = #myLib AND AND `t`.`Id` NOT IN (
SELECT DISTINCT(`f`.`Id`) FROM `folders` AS `f` JOIN `folders` AS `ff` ON (`f`.`Position` LIKE CONCAT(`ff`.`Position`, '%')) WHERE `ff`.`Active` = 1 AND `ff`.`Library` = #myLib AND `f`.`Library` = #myLib
)
ORDER BY `t`.`Position` ASC
The query works fine in mySQL and returns correct records.
To generate DQL I've tried both below options:
1.
$query = $em->createQuery("SELECT F FROM MyBundle:Folders T WHERE T.Library = :libid AND T.id NOT IN (
SELECT DISTINCT(F.id) FROM MyBundle:Folders F JOIN MyBundle:Folders FF WITH F.Position LIKE CONCAT(FF.Position, '%') AND F.Library = :libid AND FF.Library = :libid AND FF.Active = true
) ORDER BY T.Position ASC")
->setParameter('libid', $library);
$result = $query->getResult();
2.
$q1 = $this->createQueryBuilder('F')
->select('DISTINCT(F.id)');
$q1->join('\MyBundle\Entity\Folders', 'FF', 'WITH', $q1->expr()->like('F.Position', $q1->expr()->literal('CONCAT(FF.Position, \'%\')')))
->where('FF.Active = true')
->andWhere("FF.Library = '$library'")
->andWhere("F.Library = '$library'");
$q2 = $this->createQueryBuilder('T');
$q2->where('T.Library = :libid')
->andWhere($q2->expr()->notIn('T.id', $q1->getDQL()))
->setParameter('libid', $library)
->orderBy('T.Position', 'ASC');
$result = $q2->getQuery()->getResult();
In my perspective it seems OK but I don't know why in both ways it produce following exception:
ContextErrorException: Warning: Illegal offset type in
/var/www/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php line 601
Any help will be appreciated.
It seems no one has an answer for this. I found a temporary solution as below (I call it temporary because I'm changing my unique query to two separate queries and it seems the issue is in core of doctrine).
$qb = $this->createQueryBuilder('F')
->select('DISTINCT(F.id)');
$qb->join('\MyBundle\Entity\Folders', 'FF', 'WITH', 'F.Position LIKE CONCAT(FF.Position, \'%\')')
->where('FF.Active = true')
->andWhere("FF.Library = :library")
->andWhere("F.Library = :library")
->setParameter('library', $library);
$included_folders = $qb->getQuery()->getArrayResult();
$query = $this->createQueryBuilder('F')
->where('F.Active = false')
->andWhere('F.Library = :library')
->setParameter('library', $library)
->orderBy('F.Position', 'ASC');
if (!empty($included_folders)) {
if (count($included_folders) > 1)
{
foreach ($included_folders as $index => $value)
{
if (is_array($value))
{
$included_folders[$index] = !empty($value['id']) ? $value['id'] : $value[1];
}
}
$query->andWhere($query->expr()->notIn('F.id', $included_folders));
}
else {
$query->andWhere('F.id != :folder ')
->setParameter('folder', $included_folders[0]);
}
}
$result = $query->getQuery()->getResult();
As you see instead of getting the dql from my first query and putting it inside my second dql in notIn section which will lead to the warning message, I execute the first query and get the results then put the results inside notIn if amount of returned values are more than one, otherwise it should be in regular !=. This solved my problem for now, but as you see amount of transactions are now increased
If anyone has a better solution or any fix for the warning I will be thankful.
I've encountered the same error and it seems that this has been fixed in latest trunk of Doctrine/ORM.
Using "2.5.*#dev" as version in your composer.json for doctrine/orm should fix this bug and will let you do what you want in a single query.

innerjoin query in drupal 7

I am applying this query for below D6 query , not working ..dont know wat wrong i'm doing ....does innerjoin fails in some condition
$result = db_select('px_slides','s')
->join('node','n','s.vid = n.vid')
->fields('s',array('tissue_type','body_site'))
->fields('n',array('sticky','title'))
->condition('n.status','1','=')
->condition('s.cid','126','=')
->execute()->fetchObject();
drupal 6 query i have:
$result = db_query('
SELECT n.nid, n.vid, n.sticky, n.title, n.created, s.cid, s.ref_id, s.viewurl, s.specimen_type, s.tissue_type, s.body_site, s.test_type, s.algorithm, s.result
FROM {px_slides} s INNER JOIN {node} n ON n.vid = s.vid
WHERE n.status = 1 ')->execute();
You need to put your call to ->join() on a separate line altogether, as it doesn't return the query object:
$query = db_select('px_slides','s')
->fields('s',array('tissue_type','body_site'))
->fields('n',array('sticky','title'))
->condition('n.status','1','=')
->condition('s.cid','126','=');
$query->join('node','n','s.vid = n.vid');
$result = $query->execute()->fetchObject();
The join method does not chain like that. You will have to do something like:
$query = db_select('px_slides','s')
->join('node','n','s.vid = n.vid');
$query->fields('s',array('tissue_type','body_site'))
->fields('n',array('sticky','title'))
->condition('n.status','1','=')
->condition('s.cid','126','=');
$result = $query->execute()->fetchObject();
Also you can use the to string magic method to see the query it is going to execute.
$query->__toString();
Try this...
$query = db_select('px_slides', 's');
$query->innerJoin('node,'n','s.vid = n.vid');
$query->fields('s',array('tissue_type','body_site'));
$query->fields('n',array('sticky','title'));
$query->condition('n.status','1');
$query->condition('s.cid','126');
$result= $query->execute()->fetchAll(PDO::FETCH_ASSOC);

Resources