Laravel 5.2 Select Where Has Related Count Data - laravel

I have a table called 'templates' and 'details' that has relation templates has many details at my model.
i create a list template table with a filter number or detail, when i input 5 to the filter box, then table only show the templates that has 5 details.
how to do this?
this is my table structure :
templates
id | name | width | heigh
1 | A-5 | 112 | 100
2 | A-4 | 225 | 200
details
template_id | x | y
1 | 10 | 10
1 | 20 | 10
2 | 10 | 10
2 | 20 | 10
$templates = Template::whereHas( 'details', function( $detail ) {
$detail->selectRaw( 'count(id) as aduh' )->whereRaw( 'count(id) = 100' )->groupBy( 'id' );
} );

I think this should work:
$templates = Template::has('details', '=', 5)->get();
This will return all Templates that has 5 details.

Related

How Products is order by relation in Laravel?

How can I sort the products in table1 according to their connection with table2 i.e. sort the products in table1 by example_relation in table2?
Table1
| id | product |
|----|---------|
| 1 | pro1 |
| 2 | pro2 |
| 3 | pro3 |
| 4 | pro4 |
| 5 | pro5 |
Table2
| id | example_relation | product_id |
|----|------------------|------------|
| 1 | 700 | 1 |
| 2 | 800 | 2 |
| 3 | 900 | 3 |
| 4 | 850 | 2 |
| 5 | 600 | 4 |
| 6 | 125 | 5 |
Table1 model page:
public $belongsTo = [
'pro_relation' => [
'models\Model',
'key' => 'id',
'otherKey' => 'product_id',
],
Sorting section that needs to be arranged correctly:
$query->whereHas('pro_relation', function($q) use ($postFrom,$postTo){
$q->select('example_relation END AS expose');
})->orderBy("expose", DESC);
Okay, when you want to order the result of one table from another table then you can use orderBy() inside a closure of the relationship to another table.
So from your query, you can add orderBy() like so.
$query->whereHas('pro_relation', function($q) use ($postFrom,$postTo){
$q->select('example_relation END AS expose')
->orderBy('example_relation');
});
This is work
$query->join('table2', 'table1.id', '=', 'table2.yacht_id')
->orderBy(example_relation DESC);

How to make Eloquent query for Group by, with HAVING and MAX

I have SQL query which I need to convert to Eloquent and no idea where to write MAX conditions. How it is posible to convert it without much Raw sql? Thank you!
SELECT bike_id
FROM bike_filters
GROUP BY bike_id
HAVING
MAX(bike_category_id in (416,11111)) = 1
AND MAX(bike_category_id in (5555,779)) = 1
AND MAX(bike_category_id in (5555,772)) = 1
Table Structure:
| id | bike_id | bike_category_id |
| 1 | 3 | 416 |
| 2 | 3 | 779 |
| 3 | 3 | 344 |
| 4 | 3 | 332 |
| 5 | 4 | 444 |
| 5 | 5 | 555 |
The purpose of this query is to get bike_ids, which has all parameters by the query - bike can have 20 filters, but if user searches by 5 and bike matches them, we get bike_id by this query.
For this you could use havingRaw() which would look something like:
$query = DB::table('bike_filters')
->select('bike_id')
->groupBy('bike_id')
->havingRaw('MAX(bike_category_id in (416,11111)) = 1')
->havingRaw('MAX(bike_category_id in (5555,779)) = 1')
->havingRaw('MAX(bike_category_id in (5555,772)) = 1')
->get();

Laravel: Query the models where the relationship is greater than 0

I'm doing a Laravel query to query a list of elements that his relationship is grater than 0.
The table concerts:
| ID | NAME |
|----|-----------|
| 1 | Concert A |
| 2 | Concert B |
| 3 | Concert C |
And the Position table.
| ID | concert_id | user_id | Content |
|----|----------------|------------|----------|
| 1 | 1 | 1 | xxx |
| 2 | 1 | 2 | yyy |
| 3 | 3 | 1 | zzz |
| 4 | 3 | 2 | www |
| 5 | 1 | 3 | xyx |
| 6 | 3 | 3 | rer |
The query that I need to do is, get the concerts where their position has in the content a value like $some_query$.
The code I've is the following:
$result = $this->model->whereHas('positions')
->with(['positions' => function ($query) {
$query->where('content', 'like', "%{$content}%");
}])->get();
But as far as I can tell, this will bring all the concerts, and also this is going to bring only the positions that has the desired content.
So I've two problems, the first one is I need to get the concerts that his queried positions are greather than 0.
And the second one is that also I need to bring all the positions, not only the queried ones.
Basically the query is just a way to know which concerts I need to bring.
Is there possible to achieve this on a single query?
You'll have to move your query to the whereHas.
If I understood well, this is what you want:
$result = $this->model
// Take the Concerts that has positions with a similar content
->whereHas('positions', function ($query) use ($content) {
$query->where('content', 'like', "%{$content}%");
})
// Take (all) the Positions of these concerts
->with('positions')
->get();

How can i get all date even dates that don't have a record by eloquent with group by?

I have a method that get a month parameter to select rows of that month from users table. I want to show count of registered user for a month.
public function registeredUsersDaily($month)
{
$countOfDailyRegisteredUsersForAMonth = User::user()
->where(DB::raw('created_at'), '=', $month)
->groupBy('date')
->orderBy('date')
->get([
DB::raw('DATE(created_at) as date'),
DB::raw('COUNT(*) as count')
]);
dd($countOfDailyRegisteredUsersForAMonth);
}
It return count only for dates that exists in users table, so i want to have zero for dates that don't exists.
|date|count|
| 5 | 10 |
| 15 | 3 |
I want to have a result like this:
|date |count |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 10 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0 |
| 13 | 0 |
| 14 | 0 |
| 15 | 3 |
....
Please check out like this
$dateValues = array_column($countOfDailyRegisteredUsersForAMonth, "date");
$maxDate = max($dateValues);
$likeYouWant=[];
for ($i = 1; $i <= $maxDate; $i++)
{
$likeYouWant[] = ["date" => $i, "count" => in_array($i, $dateValues) ? $countOfDailyRegisteredUsersForAMonth[array_search($i, $dateValues)]["count"] : 0];
}
print_r($likeYouWant);
If you want default date than you can mention in that migration file or you can also do that in your model from where you can retrieve data when there is no date given by user.
You can also refer this for more
How to pass default values to controller by routing in Laravel 5?
From what I've got from the comments:
I think the best thing here is to count the number of users created each day of the month. This will get you zero's in case no one registered on a given date.
With this, you'd probably loop through the dates checking the total users registered each date.
For instance, let's try to get the users created the last 30 days from now:
$results = [];
$startOfDay = now()->createMidnightDate();
for($i=0; $i<=30; $i++)
{
$total_count = User::whereBetween('created_at', [$startOfDay->subDays($i-1), $startOfDay->subDays($i)])
->count();
array_push($results[ $startOfDay->subDays($i)->format('d')], $total_count);
}
With this I think you can now work with the results from the array.

Multiple Tables Group and substract sum of columns using linq sql

Here i have two tables
Table One
+---------------+----------+------------+
| Raw Material | Size | Qty |
+---------------+----------+------------+
| A | 1 | 5 |
| A | 2 | 2 |
| A | 1 | 2 |
| B | 0 | 5 |
| B | 0 | 1 |
+---------------+----------+------------+
Table Two
+---------------+----------+------------+
| Raw Material | Size | Qty |
+---------------+----------+------------+
| A | 1 | 2 |
| A | 2 | 1 |
| A | 1 | 1 |
+---------------+----------+------------+
I want out put like
+---------------+----------+------------+
| Raw Material | Size | Qty |
+---------------+----------+------------+
| A | 1 | 4 |
| A | 2 | 1 |
| B | 0 | 6 |
+---------------+----------+------------+
Want to get substract first two tables sum of qty by grouping Rawmaterial and Size
Something like this should do the job
var result = tableA.Select(e => new { Item = e, Factor = 1 })
.Concat(tableB.Select(e => new { Item = e, Factor = -1 }))
.GroupBy(e => new { e.Item.RawMaterial, e.Item.Size }, (key, elements) => new
{
RawMaterial = key.RawMaterial,
Size = key.Size,
Qty = elements.Sum(e => e.Item.Qty * e.Factor)
}).ToList();
First we create a union of the two tables using Concat, including the information which one is additive (in Factor field), and then just do the normal grouping.
If you want the result to be List<YourTableElementType>, just replace the final anonymous type projection (new { ... }) with new YourTableElementType { ... }.

Resources