Reputation: 10218
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.
Upvotes: 0
Views: 134
Reputation: 8059
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?
Upvotes: 3
Reputation: 157839
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"]);
Upvotes: 2