Doctrine - or where? - php

I have the following query:
$query = Doctrine_Query::create()
->from('Member m')
->where("m.type='1'")
->andWhere("m.name LIKE '%$term%'")
->orWhere("m.surname LIKE '%$term%'")
->orWhere("m.company LIKE '%$term%'")
->orderBy('id DESC');
But it's not working like I want — it is ignoring type column.
What I need is result set where m.type=1 and some of other fields in this query is LIKE 'something'.

$query = Doctrine_Query::create()
->from('Member m')
->where('m.type = 1 AND m.name LIKE ?', '%'.$term.'%')
->orWhere('m.type = 1 AND m.surname LIKE ?', '%'.$term.'%')
->orWhere('m.type = 1 AND m.company LIKE ?', '%'.$term.'%')
->orderBy('m.id DESC');
Your OR conditions didn't include the first condition. It's also recommended to use the ? for your variables to ensure Doctrine escapes them.

Tom's answer is correct, although I like to keep code repetition/duplication to a minimum.
This way should also work, while being a shorter, cleaner way to do it
$query = Doctrine_Query::create()
->from('Member m')
->where('m.type = ?', 1)
->andWhere('m.name LIKE :term OR m.surname LIKE :term OR m.company LIKE :term', array(':term' => '%' . $term . '%'))
->orderBy('m.id DESC');

Related

Create SQL Query in Laravel 4.2

I am new to Laravel but I would like to create this Query(MySQL):
SELECT
*
FROM
(
SELECT
ce.empresa_id,
CONCAT(ce.nombre, ' ', ce.apellido) AS nombre,
ce.grupo_contable
FROM
cliente_empresa AS ce
UNION
SELECT
cc.empresa_id,
cc.nombre,
cc.grupo_contable
FROM
cuenta_contable AS cc
UNION
SELECT
cci.empresa_id,
cci.grupo_iva AS nombre,
cci.cuenta_contable AS grupo_contable
FROM
cuenta_contables_iva AS cci
) AS cuentasContables
WHERE
cuentasContables.empresa_id = 1
AND (cuentasContables.nombre LIKE '%a%'
OR cuentasContables.grupo_contable LIKE '%%')
Looking at Documentation I can't find the proper way to do it. Thank you.
Normally, for a query that the ORM can't manage, you would probably want to simply call \DB::raw:
$results = \DB::table('users')
->select(\DB::raw(/* your stuff here */))
However in your case, you might want to consider sticking to the ORM. It looks like you might want to try something like:
$first = DB::table('cliente_empresa')
->where('empresa_id', '=', 1);
$second = DB::table('cuenta_contable')
->where('empresa_id', '=', 1);
$results = DB::table('cuenta_contables_iva')
->where('empresa_id', '=', 1)
->union($first)
->union($second)
->get();
Obviously, you'll need to put your SELECT column statements in there as well.

Eloquent WHERE LIKE clause with more than two columns

I've been trying to do a query in Laravel that in raw SQL will be like this
"SELECT * FROM students WHERE (((students.user_id)=$id) AND (((students.name) Like '%$q%') OR ((students.last_name) Like '%$q%') OR ((students.email) Like '%$q%')))")
I follow this thread (Eloquent WHERE LIKE clause with multiple columns) and it worked fine, but only with two columns Ej:
$students = student::where(user_id, Auth::id())
->whereRaw('concat(name," ",last_name) like ?', "%{$q}%")
->paginate(9);
But if I add more than two columns then the resultant variable is always empty, no matter if what is in the variable $q match with one or more columns:
$students = student::where(user_id, Auth::id())
->whereRaw('concat(name," ",last_name," ",email) like ?', "%{$q}%")
->paginate(9)
I am pretty sure I am missing something but i can't find what it is. Thanks in advance.
You can do something like this:
$students = student::where('user_id', Auth::id())->where(function($query) use ($q) {
$query->where('name', 'LIKE', '%'.$q.'%')
->orWhere('last_name', 'LIKE', '%'.$q.'%')
->orWhere('email', 'LIKE', '%'.$q.'%');
})->paginate(9);
The above Eloquent will output SQL similar to
"SELECT * FROM students WHERE students.user_id = $id AND (students.name like '%$q%' OR students.last_name Like '%$q%' OR students.email Like '%$q%')"

Doctrine 1.2 query with array bind

I have this code:
$query = Doctrine_Query::create()
->select('*')
->from('attendanceRecord a')
->where("employeeId IN (?)", implode(",", $employeeId));
$employeeId is an array of numbers
The sql output was:
Select * from attendanceRecord a where employeeId IN ('2,4,5')
but it have quote and was wrong I want this:
Select * from attendanceRecord a where employeeId IN (2,4,5)
How can I do it correctly in doctrine?
As simple as:
$query = Doctrine_Query::create()
->from('attendanceRecord a')
->whereIn('a.employeeId', $employeeId);
Please make sure you see the official documentation before asking a question.

How can I pass parameters to the query?

I use Laravel. As you know, Laravel doesn't support UNION clause for the query. So I have to write it as raw when I want to paging the whole results. Something like this:
$results = DB::select('SELECT id, title, description, imgPath
FROM news n
WHERE n.title LIKE %$q OR n.description LIKE %$q
UNION ALL
SELECT id, title, description, imgPath
FROM productions p
WHERE p.title LIKE %$q OR p.description LIKE %$q
');
As I said, I use Laravel, So how can I pass $q to the query in Laravel? All I'm trying to do is making the query safe against SQL injections. That's why I'm trying to pass the parameters to the query rather that using them directly in the query.
In pure PHP I can do that like this:
$st = $dbh->prepare('SELECT ... WHRER col LIKE %:q');
$st->bindParam(':q', $q, PDO::PARAM_INT);
I want something like this ^ in Laravel.
Yes, there is union: https://laravel.com/docs/5.3/queries#unions
I didn't test it out, but it should looks something like this:
$first = DB::table('news')
->select(['id', 'title', 'description', 'imgPath'])
->where(function($query) use ($q) {
$query->where('title', 'like', "%$q")
->orWhere('description', 'like', "%$q");
});
$result = DB::table('productions')
->select(['id', 'title', 'description', 'imgPath'])
->where(function($query) use ($q) {
$query->where('title', 'like', "%$q")
->orWhere('description', 'like', "%$q");
})
->unionAll($first)
->get();
NOTE:
With union you won't be able to do paginate out of the box. You will need to create the paginator object by yourself as shown here: Laravel - Union + Paginate at the same time?
Your "pure PHP code" won't work either. You have to respect SQL and PDO syntax
$st = $dbh->prepare('SELECT ... WHRER col LIKE :q');
$st->bindParam(':q', "%$q");
will do.
The same with Laravel: you have to define a placeholder in the query and then send it as a parameter
$sql = 'SELECT * FROM news WHERE title LIKE :q OR description LIKE :q';
$results = DB::select($sql, ['q' => "%$q"]);

Using subqueries with doctrine / Errors with aliases

I'm trying to make a simple query with a subquery in a orWhere clause (with Doctrine).
As always, Doctrine tries to rename every aliases and completely destroys the queries...
Here's an example:
$q = Doctrine_Query::create()
->from('Actualite a')
->where('a.categorie_id =?', $id)
->orWhere('a.categorie_id IN (select id from cat.categorie as cat where cat.categorie_id =?)', $id)
->execute();
Which in MySQL would make something like:
SELECT *
FROM actualite a
WHERE a.categorie_id = 1 OR a.categorie_id IN (SELECT cat.id FROM categorie cat WHERE cat.categorie_id = 1);
Everything is right about it, but then again Doctrine destroys it:
Couldn't find class cat
Every time I try to do something a little complex with Doctrine, I have errors with aliases. Any advice or ideas about how to fix this?
Thanks!
The SQL example you've provided is fine but the corresponding Doctrine syntax has a couple of errors. Here's a clean version:
$q = Doctrine_Query::create()
->select('a.*')
->from('Actualite a')
->where('a.categorie_id = ?', $id)
->orWhere('a.categorie_id IN (SELECT cat.id FROM Categorie cat WHERE cat.categorie_id = ?)', $id)
->execute();
You should use createSubquery() to explicitely tell doctrine about your nested subquery. So your query should look something like this:
$q = Doctrine_Query::create()
->select('a.*')
->from('Actualite a')
->where('a.categorie_id = ?', $id)
;
$subquery = $q->createSubquery()
->select("cat.id")
->from("Categorie cat")
->where("cat.categorie_id = ?", $id)
;
$q->orWhere('a.categorie_id IN ('.$subquery->getDql().')')->execute();
Another example can be found here:
http://www.philipphoffmann.de/2012/08/taming-doctrine-subqueries/
I think you query should be like this add the select and remove as
$q = Doctrine_Query::create()
->select('a.id')
->from('Actualite a')
->where('a.categorie_id =?', $id)
->orWhere('a.categorie_id IN (select id from cat.categorie cat where cat.categorie_id =?)', $id)
->execute();
Try this may help you.
Thanks

Categories