I would like find the correct syntax for the SET line:
Doctrine_Query::create()
->update('Media m')
->set('m.fallback IF(m.id = ?, 1, 0)', $id) <-- not correct
->execute();
Thanks for any help!
I think that could be done with two queries:
Doctrine_Query::create()
->update('Media m')
->set('m.fallback', 1)
->where('m.id = ?', $id)
->execute();
Doctrine_Query::create()
->update('Media m')
->set('m.fallback', 0)
->where('m.id != ?', $id)
->execute();
I don't know if it suits you, but at least that will do what you want. May not work out of the box, as I don't have Doctrine 1.2 at hand, so can't test this. But I think the idea is clear :)
Related
Hi I want to know how can i do this query in Laravel 8 , I tried adding the join clause but not work as expected, i need join clause? Or maybe there is another form to do it. I search others examples but i donĀ“t see anythat help me. The query is the next:
DB::table('escandallo_p as esc')
->select("esc.material", "esc.referencia", "esc.ancho", "esc.proveedor", "esc.punto",
"esc.precio", "esc.consumo", "esc.veces", "esc.001", "esc.002", "esc.003", "esc.004",
"esc.005", "esc.006", "esc.007", "esc.008", "esc.009", "esc.010", "esc.011", "esc.um", "esc.merma", "esc.importe", "esc.tipo", "esc.xtalla", "esc.fase",
DB::raw("(select anulado from prototipos_p as p where p.prototipo = '".$scandal[0]->prototipo."' and p.tipo = 'c' and p.referencia = esc.referencia )"),
// ignore
//original query "(select anulado from prototipos_p as p where p.prototipo = ",$request->prototipo," and p.tipo = 'c' and p.referencia = esc.referencia ) as 'anulado'",
// "(select clase from prototipos_p as p where p.prototipo = ",$request->prototipo," and p.tipo = 'c' and p.referencia = esc.referencia ) as 'clase'")
//Converted query ->select('pro.anulado')->where('pro.prototipo', $request->prototipo)
// ->where("p.prototipo", "=", $request->prototipo)
->where("esc.id_escandallo", "=", $request->id_escandallo)
->where("esc.id_version", "=", $request->version)
->orderBy("id","asc")
->get();
!!!! I need to pass the esc.referencia to the sub select query
The second select is the conversion of the select inside "" ( i know this is wrong is only for explain it).
Thank you in advance for any suggestion.
Best regards
EDIT: I can solve my problem with DB::raw, but if anyone know others methos are welcome!
You need to pass callback to the join query to add the extra query to the laravel's join method,
Example from Laravel Doc:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
It is explained in Laravel's doc, Advanced Join Clauses
There is Subquery support too Subquery Joins,
Eg:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})
->get();
These two might help you to achieve what you are trying
After test joins, joinSub, whereIn and other forms of doing this, I solved my problem using the DB::raw():
DB::table('escandallo_p as esc')
->select('parameters',....,
DB::raw("(SELECT column //(ONLY ONE)
FROM table
WHERE column = '".$parameter."' ...) AS nombre"),
)
->where('column', "=", $parameter)
->orderBy("id","asc")
->get();
Products::whereIn('category_id', ['223', '15', '20'])
->where('active', 1)
->get();
How can I fix this example so that it finds the exact occurrence of category_id = 223 and 15 and 20 and also necessarily active = 1?
It makes no sense to look for exactly category_id = 15, 20 and 223, it can only be one...
But, if you still want that, your query is nearly there, you can do:
Products::where('category_id', '223')
->where('category_id', '15')
->where('category_id', '20')
->where('active', 1)
->get();
But, again, that should return an empty Collection. whereIn is a simple IN in SQL, that means it is an OR for all the values you want.
Use from this group. Because, maybe you use OR condition in future. Therefore, your condition will not work correctly.
For example
Products::query()->where(function ($query){
$query->where('category_id', '223')
->where('category_id', '15')
->where('category_id', '20');
})->where('active', 1)
->get();
Explain of query above will work like that:
Select * from products where (category_id = 223 and category_id = 15 and category_id = 20) and active = 1
Counting only columns in which, Buy_Rate is more than Sell_Rate.
My query is not resulting as per expected, it is resulting me wrong.
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->where('buy_rate', '<', 'sell_rate')->get()->count();
Inverse: If sell_rate is more than buy_rate then only, count the columns.
You can use whereColumn
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)
->whereColumn('buy_rate', '<', 'sell_rate')
->count();
Also there is no need to call get() when you need count() from query builder
laravel eloquent where don't support comparing columns. so you need use raw SQL in order to compair two columns. you can do something like,
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->whereRaw('buy_rate < sell_rate')->get()->count();
hope this helps!
I'm having this situation with Propel 1.6 and a MySQL database:
$query->usePublicationQuery("pq");
$query->condition('c1', '(YEAR(`pq.PUBLISHED_DATE`)) = ?', "2013")
->condition('c2', '(MONTH(`pq.PUBLISHED_DATE`)) = ?', "03")
->condition('c3', '(DAY(`pq.PUBLISHED_DATE`)) = ?', "01")
->combine(array('c1', 'c2','c3'), 'and', 'c123');
$query->endUse();
The mergeWith()-error appears upon invocation of the endUse()-method. It is thrown when Propel tries to merge the queries like this in ModelCriteria.php:
$primaryCriteria->mergeWith($this); // (line 941)
$primaryCriteria seems to be null. Can anyone tell me, when and why this can possibly happen?
The caveat is that Propel's useQuery() and endUse() methods RETURN new query rather that change current one. So, either rewrite whole query using method chaining:
$query
->usePublicationQuery("pq")
->condition('c1', '(YEAR(`pq.PUBLISHED_DATE`)) = ?', "2013")
->condition('c2', '(MONTH(`pq.PUBLISHED_DATE`)) = ?', "03")
->condition('c3', '(DAY(`pq.PUBLISHED_DATE`)) = ?', "01")
->combine(array('c1', 'c2','c3'), 'and', 'c123')
->endUse();
...or something like this:
$query2 = $query->usePublicationQuery("pq");
$query2->condition('c1', '(YEAR(`pq.PUBLISHED_DATE`)) = ?', "2013")
->condition('c2', '(MONTH(`pq.PUBLISHED_DATE`)) = ?', "03")
->condition('c3', '(DAY(`pq.PUBLISHED_DATE`)) = ?', "01")
->combine(array('c1', 'c2','c3'), 'and', 'c123');
$query = $query2->endUse();
How are you instantiating the $query variable? Are you sure you're not trying to do this:
$query = PublicationQuery::create()
Without more information it's going to be very difficult to troubleshoot this, please provide more code.
I'm trying to group my entity by a field (year) and do a count of it.
Code:
public function countYear()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('b.year, COUNT(b.id)')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->addOrderBy('sclr1', 'DESC')
->addGroupBy('b.year');
$query = $qb->getQuery();
die($query->getSQL());
$result = $query->execute();
//die(print_r($result));
return $result;
}
I can't seem to say COUNT(b.id) AS count as it gives an error, and
I do not know what to use as the addOrderby(???, 'DESC') value?
There are many bugs and workarounds required to achieve order by expressions as of v2.3.0 or below:
The order by clause does not support expressions, but you can add a field with the expression to the select and order by it. So it's worth repeating that Tjorriemorrie's own solution actually works:
$qb->select('b.year, COUNT(b.id) AS mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');
Doctrine chokes on equality (e.g. =, LIKE, IS NULL) in the select expression. For those cases the only solution I have found is to use a subselect or self-join:
$qb->select('b, (SELECT count(t.id) FROM \My\Entity\Album AS t '.
'WHERE t.id=b.id AND b.title LIKE :search) AS isTitleMatch')
->from('\My\Entity\Album', 'b')
->where('b.title LIKE :search')
->andWhere('b.description LIKE :search')
->orderBy('isTitleMatch', 'DESC');
To suppress the additional field from the result, you can declare it AS HIDDEN. This way you can use it in the order by without having it in the result.
$qb->select('b.year, COUNT(b.id) AS HIDDEN mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');
what is the error you get when using COUNT(b.id) AS count? it might be because count is a reserved word. try COUNT(b.id) AS idCount, or similar.
alternatively, try $qb->addOrderby('COUNT(b.id)', 'DESC');.
what is your database system (mysql, postgresql, ...)?
If you want your Repository method to return an Entity you cannot use ->select(), but you can use ->addSelect() with a hidden select.
$qb = $this->createQueryBuilder('q')
->addSelect('COUNT(q.id) AS HIDDEN counter')
->orderBy('counter');
$result = $qb->getQuery()->getResult();
$result will be an entity class object.
Please try this code for ci 2 + doctrine 2
$where = " ";
$order_by = " ";
$row = $this->doctrine->em->createQuery("select a from company_group\models\Post a "
.$where." ".$order_by."")
->setMaxResults($data['limit'])
->setFirstResult($data['offset'])
->getResult();`