laravel eloquent query group by - php

I have following structure, just attaching screenshot for reference, consider the attached image is my sql schema
This is what I am trying to get
$array = [
[
'city' => 1,
'google'=> [4,2]
],
[
'city' => 2,
'google'=> [3,2,1]
],
];
I have used Postgresql
I tried with group by though no logic behind my implementation, no magic involved in laravel
$models = Model::groupBy('city')->get();
Can anyone help to find the way?
Thought of doing it through loop but would like to know the efficient way of doing it.

$models = Model::groupBy('city')->selectRaw('city, GROUP_CONCAT(google) as google')->get();
Try this out. This would group concat the result for mysql.
$models = Model::groupBy('city')->selectRaw('city, array_agg(google) as google')->get();
as per here, there is an alternate for group_concat in Postgres.

You can query directly like this
$resultSet = DB::select(DB::raw(" SQL QUERY HERE"));
and in models you can do it like
$resultSet = DB::table('table_name')
->groupBy('column_name')
->get();
While in your case you won't need group, you will need group_concat. Have a look here
http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php
Here is what I did:
For postgreSQL use this syntax
SELECT city,
string_agg(google, ',')
FROM test
GROUP BY city

Related

Need help for my sql query to make use of AS operator [duplicate]

Lets say we are using Laravel's query builder:
$users = DB::table('really_long_table_name')
->select('really_long_table_name.id')
->get();
I'm looking for an equivalent to this SQL:
really_long_table_name AS short_name
This would be especially helpful when I have to type a lot of selects and wheres (or typically I include the alias in the column alias of the select as well, and it gets used in the result array). Without any table aliases there is a lot more typing for me and everything becomes a lot less readable. Can't find the answer in the laravel docs, any ideas?
Laravel supports aliases on tables and columns with AS. Try
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();
Let's see it in action with an awesome tinker tool
$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
// 0 => object(stdClass)(
// 'uid' => '1'
// )
// )
To use aliases on eloquent models modify your code like this:
Item
::from( 'items as items_alias' )
->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
->select( DB::raw( 'items_alias.*' ) )
->get();
This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result.
Adding DB::raw prevents laravel from adding table prefixes to aliases.
Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.
$products = DB::table('products AS pr')
->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
->orderBy('pr.id', 'desc')
->get();
Hope this helps.
To use in Eloquent.
Add on top of your model
protected $table = 'table_name as alias'
//table_name should be exact as in your database
..then use in your query like
ModelName::query()->select(alias.id, alias.name)
You can use less code, writing this:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name'));
And of course if you want to select more fields, just write a "," and add more:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));
This is very practical when you use a joins complex query
I have tried all these options and none works for me. Then I had found something in the Laravel documentation that really works.
You could try this:
DB::table('table_one as t1')
->select(
't1.field_id as id','t2.field_on_t2 as field'
)->join('table_two as t2', function ($join) {
$join->on('t1.field_id ', '=', 't2.field_id');
})->get()
Also note that you can pass an alias as the second parameter of the table method when using the DB facade:
$users = DB::table('really_long_table_name', 'short_name')
->select('short_name.id')
->get();
Not sure if this feature came with a specific version of Laravel or if it has always been baked in.
Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'",
just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')
In the latest version of Laravel 9, you can use alias name for column as:
$events = Booking::whereBetween('sessionDateTime', [$today, $nextMonth])->get(['bookings.sessionDateTime as start']); // start is an alias here

My whereJsonContains not working (Laravel 5.8)

I have problem with my laravel query.
Now I use query like this:
$courses = Course::whereJsonContains('schedule->day', 1)->get();
It doesn't work.
I'm using postgreSql 9.6 and my database and raw query look like this
http://sqlfiddle.com/#!17/88fd2/1/0
I want to select class where have schedule in day = 1
If you define the column as schedule->day, MySQL assumes that this is an array of integers. In your case it's an array of objects, so you have to target the parent array and add the property name you are looking for in the second argument.
Like so:
$courses = Course::whereJsonContains('schedule', ['day' => 1])->get();
I solved with
$courses = Course::whereJsonContains('schedule', [['day' => '1']])->get();
I solved with
$products=ProductShop::active()
->whereJsonContains('tag', [['value' => "tampa"]])->get();
If you're querying the value уоu don't need to use whereJsonContains, simply use a regular where query such as:
$courses = Course::where('schedule->day', 1)->get();`
If you want to check if day exists in Json, use whereJsonLength such as:
$courses = Course::whereJsonLength('schedule->day', '>', 0)->get();

How to write SQL query for yii2 ? "InnerJoin"

SQL query:
SELECT * FROM bd.group
INNER JOIN bd.account2group ON bd.group.id = bd.account2group.group_id
INNER JOIN bd.account ON bd.account2group.account_id = bd.account.id
WHERE bd.group.id = 8
How will it be in yii2?
There are multiple ways to get to this query using Yii2. You should probably be able to get to all these solutions by reading the docs. At https://www.yiiframework.com/doc/guide/2.0/en the 'Working with databases' should give you more than enough examples to get at least something working.
If you want to use the QueryBuilder from Yii2 it will look like this:
$query = (new \yii\db\Query)
->from('bd.group')
->innerJoin('bd.account2group', 'bd.group.id = bd.account2group.group_id')
->innerJoin('bd.account', 'bd.account2group.account_id = bd.account.id')
->where([
'bd.group.id' => 8,
]);
Then you can call $query->all(), $query->one(), or one of the other functions that the Query class holds. Check out https://www.yiiframework.com/doc/api/2.0/yii-db-query for all possible options.

How can I build a condition based query in Laravel using eloquent

I was wondering how can I build a condition based query in Laravel using eloquent?
I've found how to do it with a raw query but that that's not what I want also the answer to this question isn't that dynamic at least not as dynamic as I want it to be.
What I try to achieve is to create a dynamic WHERE query based on certain conditions, for example if the field is filled or not.
If I use the following code,
$matchThese = [
'role' => 'user',
'place' => \Input::get('location')
];
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();
The query will fail if I don't send a location as POST value. I don't want it to fail I want it to skip to the next WHERE clause in the query. So basically if there's no place given don't search for it.
Build up the query and include the ->where() clause depending on whether or not you have the location in your input:
$query = User::where('role', 'user');
$query = \Input::has('location') ? $query->where('location', \Input::get('location')) : $query;
$availableUsers = $query->take($count)->orderByRaw('RAND()')->get();
Just build the array with an if condition:
$matchThese = [
'role' => 'user',
];
if(\Input::has('location')){
$matchThese['place'] = \Input::get('location');
}
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();
$query = DB::table('table_name');
if($something == "something"){
$query->where('something', 'something');
}
$some_variable= $query->where('published', 1)->get();
You can use something like this.

Summing over multiple fields in Laravel

I'm wondering if it is possible to take the sum of multiple fields in one query using the fluent query builder.
I currently have two tables: events and attendees. Attendees belong to events and have two fields: total_raised and total_hours. What I want to do is select all events and the total amount raised/total number of hours spent on that event. Now, if I were just using SQL I would do something to the effect of:
SELECT Event.id, sum(Attendees.total_raised), sum(Attendees.total_hours)
FROM Events JOIN Attendees ON Events.id = Attendees.event_id
GROUP BY Event.id
However, I can't seem to find a way to take multiple sums at once using the fluent query builder. Is there any way to do what I'm trying to do using fluent, or should I just make it a raw SQL query?
You can use sum() i.e.:
$q = DB::table('events')
->join('attendees', 'events.id', '=', 'attendees.event_id')
->sum('total_raised')
->sum('total_hours');
If that doesn't work you can try:
...
->get(
array(
'events.id',
DB::raw('SUM(attendees.total_raised)'),
DB::raw('SUM(attendees.total_hours)')
)
);
Building on simones answer. You could do this by essentially running two queries.
$query = DB::table('events')->join('attendees', 'events.id', '=', 'attendees.event_id');
$raised = $query->sum( 'total_raised' );
$hours = $query->sum( 'total_hours' );
It depends on the situation. If it were on the admin/CMS side of things I'd be lean towards this solution. If it is on the front end it should be done in a single query which will be faster. Depending on the content it may or may not be a significant difference.
$result = DB::table('events')->join('attendees', 'events.id', '=', 'attendees.event_id')
->get( array(
DB::raw( 'SUM(attendees.total_raised) AS raised' ),
DB::raw( 'SUM(attendees.total_hours) AS hours' ),
));
I am writing this answer to help those who are in search to sum multiple fields in a single table.
If you want to sum multiple fields inside a single table so there would be no need to "join" you can simply do it likewise, assuming the table like this.
In your controller do this:
$billInfo= Bills::where('reports_id',2)->get( array(
DB::raw('SUM(Price) as total_price'),
DB::raw('SUM(balance) as total_balance'),
DB::raw('SUM(paid) as total_paid'),
));
this will result the below data:
[{"total_price":17500,"total_balance":17500,"total_paid":null}]
I am doing the same thing in my project, Here is the solution which I found. I am using Laravel 5.2 Eloquent here is the Eloquent statement.
This statement which I use in my project, Please made change according to your need.
$result = self::select("*", DB::raw('SUM(auction_amount) as total_auction_amount') , DB::raw('SUM(commission_amount) as total_commission_amount'),
DB::raw('SUM(deposit_amount) as total_deposit_amount'))
->groupBy('cp_user_id')
->get()
->toArray();
Same way you can use for your query like
$result = self::select("*", DB::raw('SUM(auction_amount) as total_auction_amount') , DB::raw('SUM(Attendees.total_raised) as total_raised'),
DB::raw('SUM(Attendees.total_hours) as total_hours'))
->with('Attendees')
->groupBy('id')
->get()
->toArray();

Categories