How can I write the below pure SQL statement in laravel without using DB:raw - laravel

I'm trying to show the total price according to month. I know how to retrieve the data with pure SQL statements but I don't know a way to apply it inside Laravel. And also I don't want to use DB::raw(). I need help!! Below is the pure SQL statement.
SELECT month(dt.created_at) as Month,SUM(dp.price) as Total_Price
FROM datapack_transactions dt
INNER JOIN datapack_packages dp ON dt.package_id=dp.id
GROUP BY month(dt.created_at);
Below is the result of the above pure SQL statement.
I want to use the Laravel Eloquent instead of using DB::raw().

Try this query:
$orders = datapack_transactions::select(
DB::raw('month(datapack_transactions.created_at) as Month'),
DB::raw("SUM(datapack_packages.price) as Total_Price")
)
->join('datapack_packages','datapack_packages.id','=','datapack_transactions.package_id')
->groupBy('datapack_transactions.created_at')
->get();
//Change model and columns as per yours

Related

Symfony3 multiple update with subquery

Is there ability to make a multiple update with subquery on Symfony3 with Doctrine query builder or DQL?
For example, I want to run this query:
UPDATE tableA
SET fieldA2 = max_field2
FROM (SELECT
field1,
max(field2) AS max_field2
FROM table
GROUP BY field1) AS subquery
WHERE subquery.field1 = tableA.field1;
I can't understand how to use $entityManager->createQuery()->update with FROM subquery.
As far as I know, it's not possible through DQL.
You need to go through a loop.
foreach($entities as entity)
{
$em->flush();
}
Else, you will consider Batch processing, or just use plain SQL. So it might be usefull to check DBAL.

Conver MySQL query with LEFT statment to Laravel Eloquent

Could anybody help to translate below query to Laravel Eloquent syntactics.
SELECT LEFT(subject , 10) FROM tbl
Thanks.
on the top of your Class, Call this
use DB;
then type this as your query
DB::table('tbl')->select('LEFT(subject , 10)')->get();

Eloquent query alternative

How can I write the following in Laravel's Eloquent?
SELECT *
FROM
( SELECT real_estate.property_id,
real_estate.amount_offered,
payee.summa
FROM real_estate
LEFT JOIN
(SELECT property_id,
SUM(amount) AS summa
FROM payments
GROUP BY property_id) payee ON payee.property_id = real_estate.property_id ) yoot
WHERE summa = 0.05 * amount_offered
Been on this for a while now and really can't get around it. Lemme explain the whole cause for the panic.
I have two tables, one for property and another for payments made on those properties. Now at any given time I will like to query for what properties have been paid for to a certain percentage hence the 0.05 which reps 5%. As it is the query works but I need an Eloquent alternative for it. Thanks
Anywhere you have subqueries in your SQL you'll need to use DB::raw with Eloquent. In this case you have a big subquery for the FROM statement, so the easiest way would be to do this:
DB::table(
DB::raw('SELECT real_estate.property_id, real_estate.amount_offered, payee.summa FROM real_estate LEFT JOIN (SELECT property_id, SUM(amount) AS summa FROM payments GROUP BY property_id) payee ON payee.property_id = real_estate.property_id)')
)
->where('summa', DB::raw('0.05 * amount_offered'))->get();
Notice I used DB::raw for the WHERE statment value as well. That's because you are doing a multiplication using a column name, and the value would otherwise be quoted as a string.
If you want to go a step further and build each subquery using Eloquent, then convert it to an SQL string and injecting it using DB::raw, you can do this:
$joinQuery = DB::table('payments')
->select('property_id', 'SUM(amount) AS summa')
->groupBy('property_id')
->toSql();
$tableQuery = DB::table('real_estate')
->select('real_estate.property_id', 'real_estate.amount_offered', 'payee.summa')
->leftJoin(DB::raw('(' . $joinQuery . ')'), function ($join)
{
$join->on('payee.property_id', '=', 'real_estate.property_id');
})
->toSql();
DB::table(DB::raw('(' . $tableQuery . ')'))->where('summa', DB::raw('0.05 * amount_offered'))->get();
In this case, the second approach doesn't have any benefits over the first, except perhaps that it's more readable. However, building subqueries using Eloquent, does have it's benefitfs when you'd need to bind any variable values to the query (such as conditions), because the query will be correctly built and escaped by Eloquent and you would not be prone to SQL injection.

Running "exists" queries in Laravel query builder

I'm using MySQL and have a table of 9 million rows and would like to quickly check if a record (id) exists or not.
Based on some research it seems the fastest way is the following sql:
SELECT EXISTS(SELECT 1 FROM table1 WHERE id = 100)
Source: Best way to test if a row exists in a MySQL table
How can I write this using Laravel's query builder?
Use selectOne method of the Connection class:
$resultObj = DB::selectOne('select exists(select 1 from your_table where id=some_id) as `exists`');
$resultObj->exists; // 0 / 1;
see here http://laravel.com/docs/4.2/queries
Scroll down to Exists Statements, you will get what you need
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('table1')
->whereRaw("id = '100'");
})
->get();
This is an old question that was already answered, but I'll post my opinion - maybe it'll help someone down the road.
As mysql documentation suggests, EXISTS will still execute provided subquery. Using EXISTS is helpful when you need to have it as a part of a bigger query. But if you just want to check from your Laravel app if record exists, Eloquent provides simpler way to do this:
DB::table('table_name')->where('field_name', 'value')->exists();
this will execute query like
select count(*) as aggregate from `table_name` where `field_name` = 'value' limit 1
// this is kinda the same as your subquery for EXISTS
and will evaluate the result and return a true/false depending if record exists.
For me this way is also cleaner then the accepted answer, because it's not using raw queries.
Update
In laravel 5 the same statement will now execute
select exists(select * from `table_name` where `field_name` = 'value')
Which is exactly, what was asked for.

Codeigniter select multiple rows?

How do I select multiple rows from SQL?
ie. $results->row(1,2,3,4,5,10)
Are you using ActiveRecord? If so, you can use the where_in() method when making your query. It's not something you do after the query is finished, as you seem to be doing in your example.
$this->db->where_in('id', array(1,2,3,4,5,10));
$query = $this->db->get('myTable');
// This produces the query SELECT * FROM `myTable` WHERE `id` IN (1,2,3,4,5,10)
See the this CodeIgniter docs section for more info on SELECT statement support.

Resources