Which of the following is most efficient one and why? - laravel

Following is the query which retrives all the order rows from the orders table
$orders = auth()->user()->orders;
or
$orders = Order::where('user_id',auth()->id())->get();
or
$orders = \DB::table('orders')->where('user_id',Auth::id())->get();
If orders table 100 000 rows then which of the above method is ideal to use?

Actually in Laravel you can use toSql method to compare the queries and see which one is the most optimized query like this:
$sql=auth()->user()->orders()->toSql();
But in the example above we see generally all of them are the same:
//First
"select * from `orders` where `orders`.`user_id` = ? and `orders`.`user_id` is not null"
//Second
"select * from `orders` where `user_id` = ?"
//Third
"select * from `orders` where `user_id` = ?"
As you see the second one and the third one are totally the same but the first one has an extra and statement and it's more reliable so I think the execution times are not different and you'd better to use the first one.

compare to laravel eloquent DB:: class is faster way to retrieve data from database but in our case we manage a application in structure way and its depend on your coding standard and module management.
i suggest to use :
$sql=auth()->user()->orders()->toSql();

Related

How to count for a substring over two tables in codeigniter

I have two tables
table1
id|name|next_field
table2
id|id_of_table1|whatelse
I do a msql query to get all entries of table1 and the number of entries in table2 who has table2.id_of_table1 = table1.id
This is my query - it works fine.
$select =array('table1.*', 'COUNT(table2.id) AS `my_count_result`',);
$this->db->select($select);
if($id!=false){ $this->db->where('id',$id); }
$this->db->from('table1 as t1');
$this->db->join('table2 as t2', 't1.id = t2.id_of_table1');
return $this->db->get()->result_array();
Now I have another field which has coma-separated data
table1.next_field = info1, info2, next,...
Now I want to check in the same way like the first query how often for example "info2" is as a part inside the table1.next_field
Is it possible, how?
After all i decide to change my database structure to make the work and handle much easier.

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.

Doctrine : subquery in DQL

I'm trying to calculate a value using DQL on one single table. Say this table is named "TABLE". It has 5 colums :
id
people_count
animal_count
region_id
type_id
The result I'm looking for is the sum of people (when grouped by region), divided by the sum of animals (when grouped by type);
The SQL would be something like that :
SELECT SUM(people_count) /
(
SELECT SUM(animal_count)
FROM TABLE t2
GROUPED BY type_id
)
FROM TABLE t1
GROUPED BY region_id
How would you do that in Doctrine using DQL?
I resolved my problem by creating another query, executing it and including the result in the first one.
This is probably not the best way to do if you are dealing with a simple example, but it was the only solution for me regarding to my code architecture.
I have a solution but I think there is probably a best solution to resolve your problem.
In any case, make two queries and import results of first query in the second can be a solution. Unfortunately, it's a low-usage for our database. More, sometimes we must execute only one SQL to sort on column result per example.
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\MyClass;
use Doctrine\ORM\EntityRepository;
class MyRepository extends EntityRepository
{
public function findWithSubQuery()
{
return $this->createQueryBuilder('a')
->addSelect(sprintf(
"(SELECT COUNT(b.id) FROM %s AS b WHERE b.a = a.id GROUP BY a.id) AS otherColumn",
MyClass::class
))
;
}
}
I use this solution. Maybe the subquery could be write with DQL ojbect rather that DQL string.

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