how to convert this SQL query to eloquent in Laravel - php

I am trying to convert this SQL query to Eloquent in Laravel
Convert SQL code to Eloquent
SELECT
session_id,
SUM(points) AS total_points
FROM
(
SELECT
session_id,
spent_points AS points
FROM
session_details
WHERE
session_id IN
(
" - Meagevy6y9ukbmFXvB7",
" - Meak6dG9iqvHWfAGQvy"
)
UNION ALL
SELECT
session_id,
price_points
FROM
template_sales
WHERE
session_id IN
(
" - Meagevy6y9ukbmFXvB7",
" - Meak6dG9iqvHWfAGQvy"
)
)
t
GROUP BY
session_id
my code in Laravel but not working
$ids = ["-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy"];
$query = DB::table('session_details')
->select('session_id',DB::raw('SUM(points) AS total_points FROM ( SELECT session_id, spent_points AS points FROM session_details
WHERE session_id IN ("'.$ids.'") UNION ALL SELECT session_id,price_points FROM template_sales WHERE session_id IN ("'.$ids.'") ) t GROUP BY session_id'))
->get();

I'd advise you to use Eloquent models & Eloquent relationships to make the query more readable.
Execute the following in your terminal to create a new model:
php artisan make:model SessionDetail
Open the file that Laravel has generated for you in /app/Models (or whatever folders your models are in), and set the table in the model by putting the following property into the model class: public $table = "session_details";
If your model does not use or have Laravel timestamps which are usually created_at & updated_at, you can also use this property to disable them in the model: public $timestamps = false;
After that, create generate another model by execute the following command in your terminal:
php artisan make:model TemplateSale
Follow the same instructions again but this time change the table name to template_sales
After you have done that, head into your SessionDetail model and make a relationship to the TemplateSale model using the following code (this must be in the model class beneath the properties):
public function template_sales() {
return $this->hasMany(TemplateSale::class);
}
After that, you can replace your query with this line of code:
$query = \App\Models\SessionDetail::select("session_id", "SUM(points) as total_points")->whereIn("session_id", $ids)->get();
To get the template sales from that query, you have to use $query->template_sales;
If I got anything wrong, please tell me & I'll fix it ASAP

There is documentation available for all the operations in your query.
For selected columns use select('column1', 'column2', ...)
For selected aggregate columns use selectRaw('sum(column) as column')
For WHERE column IN (...) use whereIn('column', $array)
For subquery tables, use Closures or Builder classes (DB::table(fn($q) => ... , alias) or DB::table($builder, alias))
For UNION ALL use unionAll() with the same syntax as subquery tables.
Option 1: Closures
$ids = ["-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy"];
$query = DB::table(function ($sub) use ($ids) {
$sub->select('session_id', 'spent_points as points')
->from('session_details')
->whereIn('session_id', [1,2])
->unionAll(function ($union) use ($ids) {
$union->select('session_id', 'price_points')
->from('template_sales')
->whereIn('session_id', $ids);
});
}), 't')
->select('session_id')
->selectRaw('sum(points) as total_points')
->groupBy('session_id')
->get();
Option 2: Builder (or translating the subqueries from the inside-out)
$ids = ["-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy"];
$union = DB::table('template_sales')
->select('session_id', 'price_points')
->whereIn('session_id', $ids);
$sub = DB::table('session_details')
->select('session_id', 'spent_points as points')
->whereIn('session_id', $ids)
->unionAll($union);
$query = DB::table($sub, 't')
->select('session_id')
->selectRaw('sum(points) as total_points')
->groupBy('session_id')
->get();
Pick whichever you prefer. Both evaluate to the same query you posted.

Related

How to create subquery with Laravel Eloquent Between two tables

hello everyone I am new in Laravel development and I am wondering how to create subquery between two tables, for example, I want to execute this query :
SELECT * FROM `contracts`
WHERE `trainer_id` = '1' OR id IN (
SELECT `contract_id` FROM `trainees`
WHERE `user_id` = '1'
)
I test it in and it works fine as I want, I want to know how to write it in Laravel eloquent
Assuming that your Model is named Contract you can use the following syntax to achieve what you want:
Contracts::where('trainer_id', '1')
->orWhere(function ($subquery) {
$subquery->whereIn('id', function ($query) {
$query->select('contract_id')
->from('trainees')
->where('user_id', '1');
})
})->get();

Why getQuery ignores soft deletes?

In Laravel, when I use getQuery function to modify my query result based on model, I'm getting all values including softdeleted. It literally forgets to include and stock.deleted_at is null in the query. Why? How can I make it filter out deleted records.
Model
class Stock extends Model
{
use SoftDeletes;
protected $dates = ['issue_date', 'expiry_date'];
...
Query (getting stock grouped by expiry_date)
$query = Stock::where('product_id', $id);
$query = $query->getQuery();
$query
->select(DB::raw(
'count(*) as total,
DATE_FORMAT(IFNULL(`expiry_date`, "0000-00-00"),"%d-%m-%Y") AS expiry_date '
))
->groupBy('expiry_date');
$result = $query->get();
I had an idea of not using getQuery(), but in this case 'issue_date' will give me an error message saying "laravel Data missing".
Use $query->toBase() instead of $query->getQuery().
$results = Stock::where('product_id', $id)->toBase()->selectRaw('
count(*) as total,
DATE_FORMAT(IFNULL(`expiry_date`, "0000-00-00"),"%d-%m-%Y") AS expiry_date
')->groupBy('expiry_date')->get();
The getQuery method simply returns the underlying query, whereas toBase first applies all global scopes (soft deletes is implemented as a global scope).
BTW, you can call select and groupBy directly on the Eloquent query itself:
$results = Stock::where('product_id', $id)->selectRaw('
count(*) as total,
DATE_FORMAT(IFNULL(`expiry_date`, "0000-00-00"),"%d-%m-%Y") AS expiry_date
')->groupBy('expiry_date')->get();
...though that would return partial Eloquent models, which is not always a great idea.

SQL exists in Laravel 5 query builder

Good morning,
I've been trying for quite a lot of time to translate this query(which returns an array of stdClass) into query builder so I could get objects back as Eloquent models.
This is how the query looks like untranslated:
$anketa = DB::select( DB::raw("SELECT *
FROM v_anketa a
WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)
Order by redni_broj limit 1"
), array( 'lv_id_user' => $id_user,
));
I have tried this, but it gives a syntax error near the inner from in the subquery:
$anketa = V_anketa::selectRaw("WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)", array('lv_id_user' => $id_user,)
)->orderBy('redni_broj')->take(1)->first();
The problem is this exists and a subquery in it. I couldn't find anything regarding this special case.
Assume each table has an appropriate Eloquent model.
V_anketa is a view. The db is postgresql.
As far as the query goes I believe this should work:
$anketa = V_anketa::whereNotExists(function ($query) use ($id_user) {
$query->select(DB::raw(1))
->from('user_poeni')
->where('anketa.id', '=', 'a.id')
->where('user_id', '=', $id_user);
})
->orderBy('redni_broj')
->first();
but I'm not clear on what do you mean by "assuming every table has an Eloquent model" and "V_anketa" is a view...
Assuming the SQL query is correct, this should work:
$anketa = DB::select(sprintf('SELECT * FROM v_anketa a WHERE NOT EXISTS (SELECT 1 FROM user_poeni WHERE anketa_id = a.id AND user_id = %s) ORDER BY redni_broj LIMIT 1', $id_user));
If you want to get back an Builder instance you need to specify the table:
$anketa = DB::table('')->select('');
If you however, want to get an Eloquent Model instance, for example to use relations, you need to use Eloquent.

Laravel eager loading with limit

I have two tables, say "users" and "users_actions", where "users_actions" has an hasMany relation with users:
users
id | name | surname | email...
actions
id | id_action | id_user | log | created_at
Model Users.php
class Users {
public function action()
{
return $this->hasMany('Action', 'user_id')->orderBy('created_at', 'desc');
}
}
Now, I want to retrieve a list of all users with their LAST action.
I saw that doing Users::with('action')->get();
can easily give me the last action by simply fetching only the first result of the relation:
foreach ($users as $user) {
echo $user->action[0]->description;
}
but I wanted to avoid this of course, and just pick ONLY THE LAST action for EACH user.
I tried using a constraint, like
Users::with(['action' => function ($query) {
$query->orderBy('created_at', 'desc')
->limit(1);
}])
->get();
but that gives me an incorrect result since Laravel executes this query:
SELECT * FROM users_actions WHERE user_id IN (1,2,3,4,5)
ORDER BY created_at
LIMIT 1
which is of course wrong. Is there any possibility to get this without executing a query for each record using Eloquent?
Am I making some obvious mistake I'm not seeing? I'm quite new to using Eloquent and sometimes relationship troubles me.
Edit:
A part from the representational purpose, I also need this feature for searching inside a relation, say for example I want to search users where LAST ACTION = 'something'
I tried using
$actions->whereHas('action', function($query) {
$query->where('id_action', 1);
});
but this gives me ALL the users which had had an action = 1, and since it's a log everyone passed that step.
Edit 2:
Thanks to #berkayk looks like I solved the first part of my problem, but still I can't search within the relation.
Actions::whereHas('latestAction', function($query) {
$query->where('id_action', 1);
});
still doesn't perform the right query, it generates something like:
select * from `users` where
(select count(*)
from `users_action`
where `users_action`.`user_id` = `users`.`id`
and `id_action` in ('1')
) >= 1
order by `created_at` desc
I need to get the record where the latest action is 1
I think the solution you are asking for is explained here http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/
Define this relation in User model,
public function latestAction()
{
return $this->hasOne('Action')->latest();
}
And get the results with
User::with('latestAction')->get();
I created a package for this: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit trait in both the parent and the related model.
class User extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class Action extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
Then simply chain ->limit(1) call in your eager-load query (which seems you already do), and you will get the latest action per user.
My solution linked by #berbayk is cool if you want to easily get latest hasMany related model.
However, it couldn't solve the other part of what you're asking for, since querying this relation with where clause would result in pretty much the same what you already experienced - all rows would be returned, only latest wouldn't be latest in fact (but latest matching the where constraint).
So here you go:
the easy way - get all and filter collection:
User::has('actions')->with('latestAction')->get()->filter(function ($user) {
return $user->latestAction->id_action == 1;
});
or the hard way - do it in sql (assuming MySQL):
User::whereHas('actions', function ($q) {
// where id = (..subquery..)
$q->where('id', function ($q) {
$q->from('actions as sub')
->selectRaw('max(id)')
->whereRaw('actions.user_id = sub.user_id');
})->where('id_action', 1);
})->with('latestAction')->get();
Choose one of these solutions by comparing performance - the first will return all rows and filter possibly big collection.
The latter will run subquery (whereHas) with nested subquery (where('id', function () {..}), so both ways might be potentially slow on big table.
Let change a bit the #berkayk's code.
Define this relation in Users model,
public function latestAction()
{
return $this->hasOne('Action')->latest();
}
And
Users::with(['latestAction' => function ($query) {
$query->where('id_action', 1);
}])->get();
To load latest related data for each user you could get it using self join approach on actions table something like
select u.*, a.*
from users u
join actions a on u.id = a.user_id
left join actions a1 on a.user_id = a1.user_id
and a.created_at < a1.created_at
where a1.user_id is null
a.id_action = 1 // id_action filter on related latest record
To do it via query builder way you can write it as
DB::table('users as u')
->select('u.*', 'a.*')
->join('actions as a', 'u.id', '=', 'a.user_id')
->leftJoin('actions as a1', function ($join) {
$join->on('a.user_id', '=', 'a1.user_id')
->whereRaw(DB::raw('a.created_at < a1.created_at'));
})
->whereNull('a1.user_id')
->where('aid_action', 1) // id_action filter on related latest record
->get();
To eager to the latest relation for a user you can define it as a hasOne relation on your model like
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class User extends Model
{
public function latest_action()
{
return $this->hasOne(\App\Models\Action::class, 'user_id')
->leftJoin('actions as a1', function ($join) {
$join->on('actions.user_id', '=', 'a1.user_id')
->whereRaw(DB::raw('actions.created_at < a1.created_at'));
})->whereNull('a1.user_id')
->select('actions.*');
}
}
There is no need for dependent sub query just apply regular filter inside whereHas
User::with('latest_action')
->whereHas('latest_action', function ($query) {
$query->where('id_action', 1);
})
->get();
Migrating Raw SQL to Eloquent
Laravel Eloquent select all rows with max created_at
Laravel - Get the last entry of each UID type
Laravel Eloquent group by most recent record
Laravel Uses take() function not Limit
Try the below Code i hope it's working fine for u
Users::with(['action' => function ($query) {
$query->orderBy('created_at', 'desc')->take(1);
}])->get();
or simply add a take method to your relationship like below
return $this->hasMany('Action', 'user_id')->orderBy('created_at', 'desc')->take(1);

How to use IN or Nesting of queires in Eloquent ORM of Laravel 4

I am converting my existing twitter clone toy project into Laravel 4. I have used codeigniter framework before and Eloquent ORM is the first ORM I have ever touched.
So I have confusion about how to do some advance queries,
Following query Is to fetch all the posts which are created by users who are being followed by current_user. This Stored procedure snippet works fine.
BEGIN
SELECT
tbl_users.id as user_id,
tbl_users.display_name,
tbl_users.username,
tbl_posts.id as post_id,
tbl_posts.post_text,
tbl_posts.`timestamp`
FROM tbl_posts , tbl_users
WHERE tbl_posts.user_id IN (
SELECT tbl_followers.destination_user_id FROM tbl_followers
WHERE tbl_followers.source_user_id = xSource_user_id
)
AND tbl_posts.user_id = tbl_users.id
ORDER BY tbl_posts.id DESC
LIMIT xLimit;
END
Table structure is like below :
users : (id)
posts : (id,src_user_id [FK], post_text )
followers : (id , dest_user_id [FK] , src_user_id [FK])
My best Guess is :
Post::where('user_id', 'IN' , Follower::where('from_user_id','=','1'))->toSql();
I have added following relationships to User model
public function posts()
{
return $this->hasMany('Post');
}
public function followers()
{
return $this->hasMany('Follower');
}
you need to use lists() to get results as array
Post::whereIn('user_id', Follower::where('from_user_id','=','1')->lists('id'))->toSql();
You can use IN in this way:
Post::whereIn('user_id', yourArray)->get();
But I suggest you to take a look at eloquent manual here, especially the relationships part

Categories