how to update two joined table with queryBuilder in symfony3 - symfony-3.3

How to update fields of two tables which are joined.
it's showing error.
message": "[Semantical Error] line 0, col 271 near 'a.artisanName':
Error: 'a' is not defined.",
"class": "Doctrine\\ORM\\Query\\QueryException",
$query = $qb->update("MainBundle:ArtisanUser", 'au')
->join("au.Artisan", 'a')
->set('au.firstName', $qb->expr()->literal($parameter['params']['firstName']))
->set('au.lastName', $qb->expr()->literal($parameter['params']['lastName']))
->set('au.email', $qb->expr()->literal($parameter['params']['email']))
->set('au.dateOfBirth', $qb->expr()->literal($dob))
->set('au.gender', $qb->expr()->literal($parameter['params']['gender']))
->set('au.profilePicture', $qb->expr()->literal($parameter['params']['profilePicture']))
->set('au.userLang', $qb->expr()->literal($parameter['params']['userLang']))
->set('au.updatedAt', $qb->expr()->literal($updatedAt))
->set('au.updatedBy', $qb->expr()->literal($parameter['params']['artisanUserId']))
->set('a.artisanName',$qb->expr()->literal($parameter['params']['ArtisanName']))
->where('au.id = ?1')
->setParameter(1, $parameter['params']['artisanUserId'])
->getQuery();
$data = $query->execute();

Related

transform SQL to createQueryBuilder

I'm trying to transform this sql
SELECT * FROM user_account
LEFT JOIN brand ON user_account.id = brand.user_id_id
LEFT JOIN influencer ON user_account.id = influencer.user_id_id'
to a createQueryBuilder, I try this but it's not working
$qb = $this->createQueryBuilder('u')
->from(Brand::class, 'brand')
->from(Influencer::class, 'influencer')
->leftJoin('brand', 'b', 'ON', 'u.id = b.user_id_id')
->leftJoin('influencer', 'i', 'ON', 'u.id = i.user_id_id');
$query = $qb->getQuery();
return $query->execute();
And I got this error
[Semantical Error] line 0, col 42 near 'brand b ON u.id': Error: Class
'brand' is not defined.
Someone can help?
Many thanks
I have never used doctrine query builder, but after reading the docs I would suggest the following solution:
$qb = $this->createQueryBuilder()
->from('user_account', 'u')
->leftJoin('u', 'brand', 'b', 'u.id = b.user_id_id')
->leftJoin('u', 'influencer', 'i', 'u.id = i.user_id_id')
$query = $qb->getQuery();
return $query->execute();
NOTE: I left b.user_id_id as it is in your example, even though I think there is a typo. Maybe this should mean b.user_id. The same for influencer.

Laravel/SQL: return rows where column Equals NOT 'something" and NULL

LARAVEL 5.4 (but probably it's a more general SQL question)
Hello! I have a table with a structure:
Suppose it's my model 'Table'.
I want a query which:
uses (receives) variables :
$id of array ['id', 'string', integer]
where string is '<' or '>'
$status_not_bad = bool;
(if true - include all rows where 'status' !== 'bad' AND 'status' IS NULL);
for example, we are given:
$id = ['id', '>', 0];
$status_not_bad = true;
Table::thisquery() ... ->get();
"get rows where status is not bad and id > 0" returns rows 1 and 3.
but if we given:
$id = ['id', '<', 3];
$status_not_bad = true;
Table::thisquery() ... ->get();
"get rows where status is not bad and id < 3" returns row 1
(it should be same query which return those results using those variables).
I've never used laravel before so my syntax could be off, but I know you want to use MySQL's ifNull function for this:
Table::where([['id', '>', 0], ['number', '>', 2])->whereRaw("IfNull(status, 'blah') <> 'bad'")->get();
Just chain your ->where() clauses. Maybe also consider wrapping them to prevent conflicting with any additional:
$results = Table::where("id", ">" 0)
->orWhere("number", ">", 2)
->orWhereNull("status")
->get();
Or, wrapped:
$results = Table::where(function($query){
$query->where("id", ">" 0)
->orWhere("number", ">", 2)
->orWhereNull("status");
})->get();
If you want to see what the actual query you're executing is, replace ->get() with ->toSql(), and use dd($result);:
$results = Table::where(...)->toSql();
dd($results);
Edit: Sounds like we need multiple wrapping queries, due to multiple conditions:
$results = Table::where(function($query){
$query->where("status", "!=", "bad")
->where("id", "<", 3); -- "status is not bad and id < 3"
})->orWhere(function($query){
$query->where("status", "!=", "bad")
->where("id", ">", 0); -- "status is not bad and id > 0"
})->get();
That should handle paired conditions as noted in your comment.

Incorrect usage of UPDATE and ORDER BY In Laravel eloquent

Iam trying to update 'sortOrder' column based on a given list of ids.
For example, if the given IDs are:
$orderList = ['id' =>'1','id' =>'5','id' =>'3']
ID of '1' => 'sortOrder column' = 1
ID of '5' => 'sortOrder column' = 2
ID of '3' => 'sortOrder column' = 3
Query statement:
$ids_array = array_pluck($orderList, 'id');
$ids_string = implode(',', $ids_array);
DB::statement(DB::raw('set #rownum=0'));
$result = DB::table('requirements')
->join('sections', 'sections.id', '=', 'requirements.section_id')
->whereIn('id', $ids_array)
->orderByRaw("FIELD(requirements.id, {$ids_string})")
->update([
'requirements.sortOrder' => DB::raw('#rownum := #rownum + 1'),
]);
But when I try to update using this query, I am getting an error:
SQLSTATE[HY000]: General error: 1221 Incorrect usage of UPDATE and ORDER BY

Drupal - Query to count all nodes of content_type "A" in which field_b is "X"

I need to make a query for a drupal site. Initially I just needed to COUNT the number of nodes for a content type:
$query = "SELECT COUNT(*) amount FROM {node} n WHERE n.type ='A'";
$result = db_query($query)->fetch();
return $result->amount;
Now I need that but only for nodes that have the field_b equal to 'X'. How can I do this?
I tried EntityFieldQuery without sucess:
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'A')
->fieldCondition('field_b', 'value', 'X');
$results = $query->execute();
return $results->amount;
Any help?
You can set the query to be a count query only by using :
$count = $query->count()->execute();

Join with conditional IN with Doctrine2

Not even sure this is possible, but it looks like it should
In my Video entity, I've got a ManyToOne associate for the Product entity
Here, I am trying to acquire all published products, and acquire the videos that belong to that product with a Join
// ProductRepository.php
public function findPublished()
{
$q = $this->getEntityManager()->createQueryBuilder();
$q->select(['p', 'v'])->from($this->getEntityName(), 'p')
->leftJoin('p.videos', 'v', 'ON', 'p IN v.products')
->where('p.published = :published')
->setParameter('published', true);
$results = $q->getQuery()->getResult();
return $results;
}
The Exception that comes back is this:
[Syntax Error] line 0, col 76: Error: Expected end of string, got 'ON'
[1/2] QueryException: SELECT p, v FROM Company\CoreBundle\Entity\Product p LEFT JOIN p.videos v ON p IN v.products WHERE p.published = :published
If your entities are mapped correctly, you don't need to specify the join condition. Try this
$q->select(['p', 'v'])->from($this->getEntityName(), 'p')
->leftJoin('p.videos', 'v')
->where('p.published = :published')
->setParameter('published', true);