how to retrieve multiple table data with multiple criteria in laravel eloquent? - laravel

I want to retrieve data from 4 different table using laravel eloquent with multiple criteria.
an Overview of my table;
table 1
id
name
table 2
id
name
year
table1_id
table 3
id
name
description
table2_id
table 4
id
name
quarter
table3_id
below are their relations
table 1
hasMany -> table 2
table 2
belongsTo ->table1
HasMany->table2
table 3
belongsTo ->table2
HasMany->table3
table 4
belongsTo ->table3
I'd like to fetch the data by resource show with two parameters
and i tried this
$Report = Table1::whereHas('tabke1', function($query){
$query->where('year', 'like','%'.$year.'%');
})
->with('table2')->whereHas('table3', function($query){
$query->where('quarter', 'like', '%'.$quarters.'%');
})
->get();
but im receiving syntax error.
How can I retrieve the data from multiple table with multiple filter?
i tried this table query to understand more what i expect
SELECT `table1`.*, `table2`.*, `table3`.*, `table4`.*
FROM `table1`, `table2`, `table3`, `table4`
WHERE ((`table2`.* year = 2019) AND (`table4`.* quarter = 1))

I reckon there are two queries to achieve the results.
The first query is something like:
Table1::whereHas('table2', function ($query) {
$query->where('year', 2019);
})
->whereHas('table2.table3.table4', function ($query) {
$query->where('quarter', 1);
})
->get();
The second query is something like:
Table1::select('table1.*')
->join('table2', 'table1.id', '=', 'table2.table1_id')
->join('table3', 'table2.id', '=', 'table3.table2_id')
->join('table4', 'table3.id', '=', 'table4.table3_id')
->where('table2.year', 2019)
->where('table4.quarter', 1)
->distinct()
->get();
Regarding performance, I prefer the second query.

Related

How can I do join with whereDoesntHave in Laravel

I'm trying to run a query in my Laravel 8.0 application. I've a problem doing join (circular) using the concept of whereDoesntHave() in Laravel. Since I'm using DB::table('...') and it has other conditions implemented, I'm having a brands table, projects table and project_associate_brand table, brand is in many-to-many relation with project, I want to find out the project counts in which brand and projects are not associated with each other, I'm trying to join the table twice one for getting projects associated with and other one to remove where it is not in relationship, so my query looks like:
$innerQuery = DB::table('brands as b')
->join('project_associate_brand as pabdoesnthave', 'b.id', '=', 'pabdoesnthave.brand_id')
->join('project_associate_brand as pab', function ($join) {
$join->on('b.id', '!=', 'pab.brand_id')
->where('pabdoesnthave.project_id', '!=', 'pab.project_id');
})
->join('projects as p', function ($join) {
$join->on('pab.project_id', '=', 'p.id')
->where('pabdoesnthave.project_id', '!=', 'p.id');
})
->select(DB::raw('b.id, b.title, COUNT(DISTINCT p.id) as projects_count'))
->whereNull('b.deleted_at')
->whereNull('p.deleted_at')
->groupByRaw('b.id');
return ProductBrandFilterResource::collection(DB::query()->fromSub($innerQuery, 't')
->select(DB::raw("
id,
`title`,
projects_count
"))
->orderBy('title', 'asc')
->groupBy('t.id')->get());
I'm unable get the desired results. To explain better I've table porject_associate_brand as:
brand_id project_id
1 1
1 2
1 3
2 1
2 3
If I want to get the list of brand where projects are not associated I get
id title project_count
1 ABC 3
2 PQR 3
For id 2 it is giving me 3 but actually it should be 1 as result.
Any better approach is appreciated. Thanks

Eloquent: Order by sum of two columns

My working SQL query is as follows:
SELECT post_id
FROM news_tags
ORDER BY (link_clicks+views) DESC
What I've tried so far in eloquent is like this:
$newsTagSaved = NewsTag::
orderBy(DB::raw("`views` + `link_clicks`"), 'desc')
->paginate(12)
->pluck('post_id');
Newstag table has many columns and views and link_clicks are two of them. Now, I'm trying to retrieve the post_id order by desc of sum of views and link_click.
How can I do it in Laravel eloquent?
Thank you!
Do something like this:
$newsTagSaved = NewsTag::select(DB::raw('views + link_clicks as score'))
->orderBy('score', 'desc')
->get();
dd($newsTagSaved);
This will return just score value. If you want to return other fields, simply add them to select. As an example:
$newsTagSaved = NewsTag::select(
DB::raw('views + link_clicks as score'),
'title',
'created_at'
)
->orderBy('score', 'desc')
->get();
dd($newsTagSaved);

Laravel join two tables with where that compares two date time columns

I have two tables that I want to run joint query on using the value of two date time columns, I have products table and sync_status tables, I want to return all products with updated_at date time greater than synced_at date time.
DB::table('products')
->join('sync_statuses', function ($join) {
$join->on('products.product_number', '=', 'sync_statuses.product_number')
->where('products.updated_at', '>', 'sync_statuses.synced_at')
->whereNull('products.deleted_at');
})
->select('products.product_number');
This SQL represents what I am trying to achieve using Eloquent:
SELECT products.product_number
FROM products
JOIN push_statuses
ON products.product_number = statuses.product_number
AND (
statuses.synced_at IS NULL
OR products.updated_at > statuses.synced_at
)
You have to use on() instead of where() to compare columns:
->on('products.updated_at', '>', 'sync_statuses.synced_at')
This worked for me:
DB::table('products')
->join('statuses', function ($join) {
$join->on('products.product_number', '=', 'statuses.product_number')
->where(DB::raw('products.updated_at'), '>=', DB::raw('statuses.synced_at'))
->whereNull('products.deleted_at');
})->select('products.product_number');
I needed to use DB::raw('products.updated_at') to reference each date time column in the where() clause.

Laravel join with limit

I have the following working for laravel paginate
$query = DB::table('clients')
->leftJoin('radusergroup', 'clients.username', '=', 'radusergroup.username')
->leftJoin('recharge', 'clients.username', '=', 'recharge.soldto');
I want to join some values from two tables radusergroup and recharge. radusergroup always return one row as it has only one row stored whereas recharge table return multiple rows. I want only one row returned from recharge table which is latest entry.
Right now its return all the possible rows from recharge table and showing it on paginated view.
This is Laravel Official documentation
DB::table('clinets')
->leftJoin('radusergroup', 'clients.username', '=', 'radusergroup.username')
->leftJoin('recharge', function ($leftJoin) {
$leftJoin->on('clients.username', '=', 'recharge.soldto')
->where('recharge.create_date', '=', DB::raw("(select max(`create_date`) from recharge)"));
})
->get();
this is the case if you have create_date column in your table, if you haven't got it I strongly recommend to create that column.

Laravel - Get an user who has specific relationships

I have a user with countries relationship. (hasMany)
user_id 1
country_id 1
user_id 1
country_id 2
...
What I want is to get those users who have both countries (country 1 and country 2) How can I do this? I'm reading http://laravel.com/docs/eloquent#querying-relations but I'm not very sure what to do.
edit: almost the solution
$users = \User::whereHas('countries', function($query) {
$countries_ids = [1, 2, 4];
$query->whereIn('users_countries.country_id', $countries);
})->get();
This will work as long as there are no duplicates in the pivot table (unique index for pair of fk keys for example):
$countries = [1,5,9];
User::whereHas('countries', function ($q) use ($countries) {
$q->whereIn('users_countries.country_id', $countries);
}, '=', count($countries) )->get();
In case there are duplicates, like:
user_id | country_id
1 | 1
1 | 2
1 | 1
Then you would need raw count(distinct ...) so you couldn't use whereHas, so I suggest this, which will be much faster:
$countries = [1,5,9];
User::join('users_countries as uc','uc.user_id', '=', 'users.id')
->whereIn('uc.country_id', $countries)
->having(DB::raw('count(distinct uc.country_id)'), '=', count($countries))
->groupBy('users.id')
->get(['users.*']);
You can do it the other way. Make the query on the country model. Add a function in the country model
public function user(){
return $this->belongsTo('user');//or if there is no user_id column in the countries table, use the ('model','local_key','foreign_key') pattern.
}
Then create an array with the country_ids, and que the country model.
$country_ids=array(4,67);
$countries=Country::where('id',$country_ids[0])->where('id',$country_ids[1])->get();
In order to get the users you should loop through like this
foreach($countries->user as $user)

Resources