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.
Related
I have two tables ad_pool and advertisment. ad_pool has some data while advertisment is empty. I am using this code to select values from the first table by not equal query like this andWhere(['<>','fisttablekey','second_tbl_key']). This is the complete code i am using to retrieve the data and i also uploaded the image.
$pool1 = (new Query())>select('p.id,p.cleaner_user_id,p.ad_place_id')
->from('ad_pool p')
->innerJoin('advertisment a' , 'p.id = a.pool_id')
->where(['=','ad_place_id',1])
->andWhere(['<>','p.id','a.pool_id'])
->orderBy(new Expression('rand()'))
// ->limit(1)
->all();
var_dump($pool1);
exit();
this return me Empty array. need your kind help. Thanks in advance.
The INNER JOIN keyword selects records that have matching values in both tables.
Since your advertisement is empty, it won't return any data. You can use LEFT JOIN instead.
$pool1 = (new Query())>select('p.id,p.cleaner_user_id,p.ad_place_id')
->from('ad_pool p')
->leftJoin('advertisment a' , 'p.id = a.pool_id')
->where(['=','ad_place_id',1])
->andWhere(['<>','p.id','a.pool_id'])
->orderBy(new Expression('rand()'))
->all();
W3Schools Reference
This way I solved this problem after 3 to 4 hours hardwork. Get the required values from the second table if there is any and then convert it into single array and used it in the NOT IN condition. (we must have passion of helping others and we should help each other).
I have this code in a laravel project
$state_query = Advertisement::active()
->notExpired()
->inTime()
->network($network)
->textbook($textbook, $textbook_category_id, $book_category_id)
->grade($grade)
->state($state_id);
$city_query = Advertisement::active()
->notExpired()
->inTime()
->network($network)
->textbook($textbook, $textbook_category_id, $book_category_id)
->grade($grade)
->city($city_id);
$district_query = Advertisement::active()
->notExpired()
->inTime()
->network($network)
->textbook($textbook, $textbook_category_id, $book_category_id)
->grade($grade)
->district($district_id);
$result = $state_query
->union($city_query)
->union($district_query);
now, I want to make "$result" variable as a database table and use "where" and "sum" eloquent functions on it
how can I do that?
Simply make a collection :
https://laravel.com/docs/5.3/collections
The results of Eloquent queries are always returned as Collection instances.
I need to execute 3 quires when user comes to main page.
public function index()
{
$slider = \App\Slider::select("title", "poster", "link", "sub_title")->translate()->orderBy("created_at", "asc")->get();
$services = \App\Page::getPage(24)->tabs()->translate()->get();
$partners = \App\Partner::select('id', 'title', 'link')->translate()->get();
return view('Front/index', compact('slider', 'services', 'partners'));
}
as you can see, I need to get images from slider, take page data and take some company partners info. so i execute 3 quires to get what i want. is there way to make only one query and union all these 3 quires in one? I want something like multi_query function in php. no matter it would be in eloquent or query builder.
p.s. I don't eloquent relationships, these data aren't related to each other
just put ur query inside $qry=DB::select("your_query");
return view('your_view',compact('qry'));
you can see following also for better unterstand
$emp_id="5623";
$var_start_date=$request->startdate;
$data_query= DB::select("SELECT orinfo.*,
chinfo.name as chname
FROM order_info orinfo, ch_info chinfo
WHERE orinfo.ch_id= chinfo.ch_id
AND orinfo.emp_id= ?
AND
to_char(orinfo.order_Date,'mm/dd/yyyy') BETWEEN ? AND ? order by orinfo.order_Date desc",[$emp_id,$var_start_date,$var_end_date]);
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
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();