Convert Raw SQL Query to Laravel Eloquent using eager loading - laravel

I'm having great difficulty in trying to convert the following query into an Eloquent one.
SELECT Sum(t.amount) AS amount,
m.name
FROM transactionsv2 t
JOIN channels c
ON t.entityid = c.uuid
JOIN merchants m
ON c.sender = m.uuid
WHERE t.paymenttype = 'DB'
AND t.status = 1
AND t.processing_time >= '2019-01-01'
AND t.processing_time < '2019-01-21'
GROUP BY m.name;
This is what I have but the result set is not right...
public function getTransactionsVolumeReport()
{
$report = Transaction::select(DB::raw('sum(amount) as amount, entityId'))
->where('paymentType', '=', 'DB')
->where('status', 1)
->where('processing_time', '>=', '2019-01-01 00:00:00')
->where('processing_time', '<=', '2019-01-21 23:59:59')
->with(['channel' => function ($q) {
$q->select('uuid', 'name', 'sender');
}])
->with(['channel.merchant' => function ($q) {
$q->select('uuid', 'name')
->groupBy('name');
}])
->get();
echo $report;
}
These are the queries that Laravel debugbar is showing...
Below are my Eloquent relationships...
Transaction Model
protected $with = ['channel', 'statusPayment'];
public function channel() {
return $this->hasOne(Channel::class, 'uuid', 'entityId');
}
-----
Channel Model
protected $with = ['merchant', 'attachedMerchantAccount'];
public function merchant() {
return $this->hasOne('App\Merchant', 'uuid', 'sender');
}

Related

Laravel How to get `->sum('count')` in `whereHas` subquery?

I have 3 model Transaction , Cart , Acceptedcart.
in Cart model I have transaction_id and in Acceptedcart model have cart_id.
in Transaction.php my relationship to carts:
public function carts()
{
return $this->hasMany(Cart::class);
}
in Cart.php my relationship to accepted carts :
public function accepted_carts()
{
return $this->hasMany(Acceptedcart::class);
}
And the query to get the transactions where acceptedcart->sended== false:
$transactions = Transaction::whereHas('carts.accepted_carts', function ($query) {
$query->where('sended', false);
})->get();
Now I want to get sum() of count column in acceptedcart, where I can set the sum()?
$transactions = Transaction::whereHas('carts.accepted_carts', function ($query) {
$query->where('sended', false);
})->sum('count);
Or
$transactions = Transaction::whereHas('carts.accepted_carts', function ($query) {
$query->where('sended', false)->sum('count');
})->get();
is there Only one way that foreach on the ->get() result ?
Try this
Transaction.php
public function accepted_carts()
{
return $this->hasManyThrough(Acceptedcart::class, Cart::class);
}
Query
$transactions = Transaction::query()
->whereHas('accepted_carts', fn ($query) => $query->where('sended', false))
->withCount([
'accepted_carts' => fn ($query) => $query->select(DB::raw('SUM(count) as accepted_carts_sum'))
])
->get();

Laravel whereHas Filter sub relation

Is that any method to filter the employees and the manpower table record does not return also?
$result = Pwra::with('purchaseOrder', 'manpower')
->where('pwra_dt', $date)
->where('time_session', $session)
->whereHas('manpower.employees', function ($q) {
$q->where('status', 1);
})
->get();
Pwra Class
public function manpower()
{
return $this->hasMany('App\Models\Manpower', 'pwra_uuid', 'pwra_uuid');
}
Manpower Class
public function employee()
{
return $this->hasOne('App\Models\Employees', 'employees_uuid', 'employees_uuid')->where('status', 1);
}
What I expected is: When the employees Status = 0, it will not return any record even manpower.
you can try 2 level whereHas()
$result = Pwra::with('purchaseOrder', 'manpower')
->where('pwra_dt', $date)
->where('time_session', $session)
->whereHas('manpower', function ($q) {
$q->whereHas('employees',function($subQ){
$subQ->where('status', 1);
});
})
->get();
whereHas('manpower.employees' it will not work

How to do this query in laravel with eloquent?

I have this DB:
[Database model]
This is the query I want to make in Laravel:
SELECT
product_translations.name,
product_translations.description,
products.ean_code
FROM product_translations, products, languages
WHERE product_translations.language_id = languages.id
AND products.id = product_translations.product_id
AND languages.language_code = "en";
Relationships in Laravel:
class Product extends Model
{
public function translations ()
{
return $this->hasMany(ProductTranslation::class, 'product_id');
}
}
class ProductTranslation extends Model
{
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
public function language()
{
return $this->belongsTo(Language::class, 'language_id');
}
}
class Language extends Model
{
public function ProductTranslations()
{
return $this->hasMany(ProductTranslation::class, 'language_id');
}
}
is this correct? the raw query works.
thanks
The query syntax you are using is an old style syntax and will produce inner joins for tables. Using laravel you can use builtin methods to query data from your related models.
For your question I believe you need products list but with specific translation
$products = Product::with(['translations' => function($query)
{
$query->join('product_translations as pt', 'products.id', '=', 'pt.cart_id')
->join('languages as l', 'l.id', '=', 'pt.language_id')
->where('l.language_code', '=', 'en')
->first();
}])->get();
Or if you want to go with query builder you can write as
$products = DB::table('products AS p')
->select([
'p.id',
'p.is_organic',
'pt.name',
'pt.description',
'pt.ean_code'
])
->join('product_translations AS pt', 'pt.product_id', '=', 'p.id' )
->join('languages AS l', 'pt.language_id', '=', 'l.id')
->where('l.language_code','en')
->get();
In SQL
SELECT
p.id,
p.is_organic,
pt.name,
pt.description,
pt.ean_code
FROM products p
INNER JOIN product_translations as pt ON pt.product_id = p.id
INNER JOIN languages l ON pt.language_id = l.id
WHERE l.language_code = "en";

Laravel: multiple where clauses in a many-to-many relationship

I am not able to create this sql query on laravel:
select * from `events_theatre` where
event_id IN (
select id from events where (`events`.`id` = `events_theatre`.`event_id` and `user_id` = 1 and `event_type` ='theatre') and `events`.`deleted_at` is null
)
or event_id IN (
select id from events inner join events_managers on events.id = events_managers.event_id and events_managers.user_id = 1
)
and `events_theatre`.`deleted_at` is null
The Events_Theatre model has this relationship:
public function event()
{
return $this->hasOne('App\MyEvent', 'id');
}
While the MyEvent model has this relationship:
public function managers()
{
return $this->belongsToMany('App\User', 'events_managers', 'event_id', 'user_id');
}
Pratically an Events_Theatre model is an Event model, and an Event model may have many managers but just 1 admin.
I need to get that Events_Theatre (and their MyEvent) whose user is an admin or one of the managers.
I tried with this eloquent query:
$list = App\Events_Theatre::whereIn('event_id', function ($query) {
$query
->where(['user_id' => Auth::id(), 'event_type' => 'theatre'])
->orWhereHas('managers', function ($query) {
$query->where('user_id', Auth::id());
});
});
But I get this sql query:
select * from `events_theatre` where
exists (
select * from `events` where (
`events`.`id` = `events_theatre`.`event_id` and `user_id` = 1 and `event_type` = 'theatre'
) or exists (
select * from `users` inner join `events_managers` on `users`.`id` = `events_managers`.`user_id` where `events_managers`.`event_id` = `events`.`id` and `user_id` = 1
)
and `events`.`deleted_at` is null
) and `events_theatre`.`deleted_at` is null
But its wrong. How can I solve this?
Thanks
UPDATED
I got the answer. This is the eloquent code I used:
$list = Events_Theatre::whereHas('event', function ($query) {
$query
->where(['user_id' => Auth::id(), 'event_type' => 'theatre']);
})->orWhereHas('event', function ($query) {
$query
->whereHas('managers', function ($query) {
$query->where('user_id', Auth::id());
});
})->get();
You can try has method
App\Events_Theatre::has('event')->orhas('managers')->get();

query with Laravel Eloquent ORM

How can I make this query in Laravel, using Eloquent ORM?
select * from posts p order by ( select count(*) from likes where flag = 'c' and p.id = post_id ) Desc limit 3
I have this relationship in my models
Post.php
public function likes(){
return $this->hasMany('Like', 'post_id');
}
Like.php
public function post(){
return $this->belongsTo('Post', 'post_id');
}
Thanks! :)
You may try something like this:
$posts = Post::leftJoin('likes', function($join) {
$join->on('posts.id', '=', 'likes.post_id')->where('flag', '=', 'c');
})
->select('posts.*', 'likes.post_id', DB::raw('count(likes.post_id) as pCount'))
->groupBy('post_id')
->orderBy('pCount', 'desc')
->take(3)
->get();

Resources