Ok, so I'm needing to create a query below in eloquent or Laravel in some matter. I'm just not sure how I would create something like this:
select * from
(select * from Bulk
where Login = 'moga' and ApptDate='2015-02-25'
order by FormatTime asc) as A
group by Name
This query will run just fine as a raw query in the database, I'm just not sure how I would pull this query off using query helper or eloquent.
You can use either Eloquent or Query Builder. Here's an example with the Query Builder:
DB::table(DB::raw('(select * from Bulk where Login = "moga" and ApptDate="2015-02-25" order by FormatTime asc) as A'))
->groupBy('Name')
->get();
With Eloquent you'd use ModelName::from() instead of DB::table(). But keeping in mind that DB::raw does not escape variable values inserted into the query string, you could build the nested query using the builder as well, to make sure you're not vulnerable to SQL injection:
$from = DB::table('Bulk')
->where('Login', $login)
->where('ApptDate', $date)
->orderBy('FormatTime')
->toSql();
DB::table(DB::raw('(' . $from . ') A'))->groupBy('Name')->toSql();
Related
Is it possible in Laravel, using eloquent to get the raw SQL query generated by the ORM query ?
Also, is it possible to get an array of all the columns involved in that query ?
Consider for exemple that Eloquent query:
$query = Category::join('posts', 'post.category_id', '=', 'category.id');
Would it be possible to retrieve in the code, the raw SQL of that query, and most importantly, an array of the columns involved ? In this cas, the columns of the Category and the Post models (category.id, category.name, post.id, post.title, post.category_id, etc...)
You can enable ORM logging with:
DB::enableQueryLog();
// query
and when your query executed you can get it with:
DB::getQueryLog();
You can use toSql() and getBindings() and for query builder same as:
$sql = $query->toSql();
$bindings = $query->getBindings();
If you do not provide any fields it will default to *
I have an SQL query I want to build with symfony/Doctrine2 QueryBuilder.
select
(SELECT group_concat(DISTINCT sender)
FROM transactions) as senders,
(SELECT group_concat(DISTINCT receiver)
FROM transactions) as receivers,
(SELECT group_concat(DISTINCT message_type)
FROM transactions) as types
As seen in the description above, the main-query doesn't have a table
Is there a way to implement this in Querybuilder without writing the SQL Command as it is shown?
According to:
The same way you build a normal Query, you build a QueryBuilder object, just providing the correct method name. Here is an example how to build a QueryBuilder object:
//$em instanceof EntityManager
// example1: creating a QueryBuilder instance
$qb = $em->createQueryBuilder();`
http://doctrine-orm.readthedocs.io/en/latest/reference/query-builder.html#constructing-a-new-querybuilder-object
But this will require your root query to map against an entity. Also the querybuilder doesn't provide any real support for subqueries, but there are some examples on how to achieve is anyway:
// build root query
$query = Doctrine_Query::create()
->from('Movie m')
->where('name = ?', 'Prometheus')
;
// build subquery
$subquery = $query->createSubquery()
->from('SeenMovie sm')
->where('m.name = sm.name')
;
// nest subquery and execute
$query->where('EXISTS (' . $subquery->getDql() . ')')->execute();
Borrowed from: https://www.philipphoffmann.de/2012/08/29/a-bulletproof-pattern-for-creating-doctrine-subqueries-of-any-complexity/
I'm unsure what whereRaw is in PHP Laravel framework. Could you provide good and easily understandable example, please?
WhereRaw() is a function of Laravel query builder which puts your input as it is in the SQL query's where clause.
Think of it as the where() function whose input argument will not be processed before inserting into queries.
See the example below:
$Query = DB::table('some_table')->where('YEAR(date)', 'YEAR(CURRENT_DATE)');
In this Laravel will resolve your arguments to build a query. Which will result in the following query because your input will be treated as some field and its its value :
SELECT * FROM `some_table` WHERE `YEAR(date)` = `YEAR(CURRENT_DATE)`
Which is not desired.
And now if you use whereRaw like:
$Query = DB::table('some_table')->whereRaw('YEAR(date) = YEAR(CURRENT_DATE)');
Now Laravel put this where clause as it is in your query, like below:
SELECT * FROM `some_table` WHERE YEAR(date) = YEAR(CURRENT_DATE)
Hope it helped (:
WhereRaw: Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings.
If you are unable to generate the query you need via the fluent interface, feel free to use whereRaw()
Ex:
$users = User::whereRaw('age > ? and votes = 100', array(25))->get();
which is equals to:
"SELECT * FROM users WHERE age > 25 AND votes = 100";
Reference
In laraval we use query builder. But Sometime you need to execute raw sql query.
So you can inject it to whereRaw as this example :
whereRAW('YEAR(event_datetime) =?', [$year])
I have this query in laravel 5.2
$obj_custom_stdy_data = QstCustomStudyData::where('student_id', $this->data_user['student_id'])
->select($list_id . ' as list_id ', 'chapter_id', 'subject_id', 'subject_code_id')
->get()
->toArray();
Well I have a fixed value $list_id got from top code. Actually I want to add new field during query selection as list_id. However I got error for such that method.
When I tried in mysql IDE for example:
SELECT (1+2) as total, c.* FROM users
Then the result is no wrong at all.
Is that anyway to write in query builder for laravel instead of raw style?
You can take the use of DB::raw() method of QueryBuilder like this:
->select(DB::raw('(1+2) as total'));
See more about Query Builder's Raw Expressions
Hope this helps!
I would like to know how can I execute a query, inside a phalcon controller, using parameters.
My SQL Query:
SELECT a.*, getApplicationData(a.id) as json_data
FROM application a
INNER JOIN application_data d on d.application_id = a.id
WHERE a.form_id=1
AND d.firstname LIKE '%:searchQuery:%' ;
Here is how I'm trying to execute (I found it in Phalcon's doc, but the example was not inside a controller).
$applications = $this->db->query(
$sqlQuery,
array('searchQuery'=>$searchQuery)
)->fetchAll();
I know that since you have the ORM I shouldn't be querying the DB like this, but for the feature I'm working on it has to be like this, this query is dymanic.
My question is how to pass the parameter for the :searchQuery: in the query.
Thanks in advance for any help.
You almost got it right. You only had to add the percents (%) in the bind array.
$sqlQuery = 'SELECT * FROM events WHERE title LIKE :searchQuery';
$applications = $this->db->query(
$sqlQuery,
array('searchQuery'=> '%' . $searchQuery . '%')
)->fetchAll();
Also notice how I binded the :searchQuery in the $sqlQuery. It only uses single : instead of surrounding the parameter. This is because Raw queries use directly the DB connection in our case it is PDO.
More examples can be found here: https://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter_Pdo.html