I have a query
$orders = DB::table('orders')->where('user_id', $user->id)->get();
And this is what I have in view:
#foreach ($orders as $order)
{{ $order->id }}
#endforeach
It prints out 1 2 3, because the table has these three IDs.
But if I try to join, I get a rather unpredicted result.
$orders = DB::table('orders')->where('user_id', $user->id)->
leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
It gives 2 1 1. Result is the same with rightJoin() and join().
I thought this command would append row from status table to every corresponding row of orders table. Join on orders.status_id = status.id.
Can I get an intended result?
I have tried ->select('orders.*') but it did not change the result.
But still, I needed to alias everything out, as suggested in the comments here. So here is my final query.
$orders = User::find($user->id)->orders()->
select('orders.id as order_id', 'status.id as status_id',
'status.label as label', 'orders.ordered_at as ordered_at')
->leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
Probably this could be done in more pretty way, but this works.
Thank you who commented the post.
UPD: Now, I have fixed relations between my models and I can do this much simpler. As described here Laravel Many-to-one relationship
$orders = Order::with('status')->where('user_id', '=', $user->id)->get();
I want print a table from database on view page with where condition, means I want print table of student where class is seven and fee status is paid.
How we do this?
i tried it but not work:
<?php
$students = $this->db->get_where('student' , array('status' => paid,'class_id'=>7))->result_array();
foreach($students as $row):?>
I have used this code to find the answer for you Please see it and try it out
$query = $this->db->get_where('tasks', array('description' => 7,'status' => 1));
echo "<pre>";
print_r($query->result_array());
change your array element as this since paid is a string it must be in quots
array('description' => "paid",'class_id'=>7)
For some time I have struggled with what I think should be a simple display of a joined result. My code is as follows.
<h1>start test</h1>
<?php
ee()->db->from('store_orders as so');
ee()->db->join('store_order_items as si', 'so.id = si.order_id', 'inner');
$query = ee()->db->get();
echo '<h1>This is a list of all the channel titles999</h1>';
?>
<ul>
<?php
// print_r($query->result());
foreach($query->result() as $row)
{
echo '<li>' . $row->id . ' - ' . $row->order_id . ' - ' . date('m/d/Y:G:i:s', strtotime($row->order_date)) . '</li>';
}
?>
</ul>
In the foreach loop I want to display the results of the join to make sure that the order id is equal across the 2 tables.....it is not.
I've tried inner, outer, left and right on the join, each giving different results but never what I think should be the correct result...both fields should be the same.
Any help or insight would be appreciated.
BTY, I model my query in MS Access to get my basic syntax.
Thanks
Anthony Jaxon, Los Angeles, CA USA
Because you do a SELECT * and both table have a field called "id", MySQL doesn't know which one you want.
You need to set an aliase to your fields
ee()->db->select('so.id, si.order_id, so.order_date');
ee()->db->join('store_order_items si', 'so.id = si.order_id');
$query = ee()->db->get('store_orders so');
I have a table that contains, amongst other columns, a column of browser versions. And I simply want to know from the record-set, how many of each type of browser there are. So, I need to end up with something like this: Total Records: 10; Internet Explorer 8: 2; Chrome 25: 4; Firefox 20: 4. (All adding up to 10)
Here's my two pence:
$user_info = Usermeta::groupBy('browser')->get();
Of course that just contains the 3 browsers and not the number of each. How can I do this?
This is working for me:
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->get();
This works for me (Laravel 5.1):
$user_info = Usermeta::groupBy('browser')->select('browser', DB::raw('count(*) as total'))->get();
Thanks Antonio,
I've just added the lists command at the end so it will only return one array with key and count:
Laravel 4
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->lists('total','browser');
Laravel 5.1
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->lists('total','browser')->all();
Laravel 5.2+
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->pluck('total','browser');
If you want to get collection, groupBy and count:
$collection = ModelName::groupBy('group_id')
->selectRaw('count(*) as total, group_id')
->get();
Cheers!
Open config/database.php
Find strict key inside mysql connection settings
Set the value to false
Works that way as well, a bit more tidy.
getQuery() just returns the underlying builder, which already contains the table reference.
$browser_total_raw = DB::raw('count(*) as total');
$user_info = Usermeta::getQuery()
->select('browser', $browser_total_raw)
->groupBy('browser')
->pluck('total','browser');
Try with this
->groupBy('state_id','locality')
->havingRaw('count > 1 ')
->having('items.name','LIKE',"%$keyword%")
->orHavingRaw('brand LIKE ?',array("%$keyword%"))
$post = Post::select(DB::raw('count(*) as user_count, category_id'))
->groupBy('category_id')
->get();
This is an example which results count of post by category.
Laravel Version 8
Removed the dependency of DB
$counts = Model::whereIn('agent_id', $agents)
->orderBy('total', 'asc')
->selectRaw('agent_id, count(*) as total')
->groupBy('agent_id')
->pluck('total','agent_id')->all();
Another way would be this:
$data = Usermeta::orderBy('browser')->selectRaw('browser, count(*) as total')->get()
Since this is the top result when i search for eloquent count with groupby returns only first
using "illuminate/database": "^9.38" in composer. so "should" be the latest at the time of this post
I honestly have no idea why they think that returning the first record is the right option.. ie
IMHO the current implementation doesn't make sense for queries including groupBy statements.
Why should be N_1 be the "right" result?
Since #taylorotwell rightly pointed out some performance issues with counting the subquery results, why don't we fix that on the php side, by checking if there are any group statements, and if so, performing a N_1 + N_2 + .... + N_M ?
https://github.com/laravel/ideas/issues/1693#issuecomment-621167890
Wrapping the query and doing a count seems to work for me
$records = ...
$record_count = DB::table( "fake" );
$record_count->fromSub($records->select(DB::raw(1)),"query");
$record_count->count();
create a "fake" query builder
add a sub "from" from (...) query set the "sub query" to select 1 instead of returning huge column data. not sure if this is needed but in my mind it seems like a good idea
do the normal ->count()
returns the "expected" result since it executes:
select count(*) as aggregate from (select 1 from ... group by ...) as `query`
The sub is the "query" that $records would normaly execute
My use-case is for pagination (not using laravel). so i get the record count then pass it to the paginator then call ->forPage()->get()
https://github.com/laravel/framework/issues/44081#issuecomment-1301816710
Laravel Eloquent query that uses the GROUP BY clause with advanced aggregation functions and conditional statements.
GroupBy on one column.
$data = Employee::select(
'department',
DB::raw('SUM(salary) as total_salary'),
DB::raw('COUNT(*) as total_employees'),
DB::raw('SUM(IF(bonus > 13000, 1, 0)) as employees_with_bonus')
)
->groupBy('department')
->havingRaw('total_employees > 5 AND total_salary > 10000')
->orHavingRaw('department_rank LIKE ?', array("%$keyword%"))
->get();
In the above query, if the bonus is greater than 13000, the IF function returns 1 otherwise it returns 0.
GroupBy on two columns: The groupBy method takes multiple arguments
$data = Employee::select(
'department',
'location',
DB::raw('SUM(salary) as total_salary'),
DB::raw('COUNT(*) as total_employees'),
DB::raw('SUM(IF(bonus > 1000, 1, 0)) as employees_with_bonus')
)
->groupBy('department', 'location')
->havingRaw('total_employees > 5 AND total_salary > 10000')
->get();
GroupBy and JOIN: Laravel Eloquent query that joins two tables and uses grouping and aggregate functions. (inner join)
$data = Employee::select(
'employees.department',
'employees.location',
DB::raw('SUM(employees.salary) as total_salary'),
DB::raw('COUNT(*) as total_employees'),
DB::raw('SUM(IF(employees.bonus > 1000, 1, 0)) as employees_with_bonus')
)
->join('departments', 'employees.department', '=', 'departments.name')
->groupBy('employees.department', 'employees.location')
->havingRaw('total_employees > 5 AND total_salary > 10000')
->get();
Raw MySQL Query:
SELECT
department,
SUM(salary) AS total_salary,
COUNT(*) AS total_employees,
SUM(IF(bonus > 1000, 1, 0)) AS employees_with_bonus
FROM
employees
GROUP BY
department
HAVING
total_employees > 5 AND total_salary > 13000;
If you want to get sorted data use this also
$category_id = Post::orderBy('count', 'desc')
->select(DB::raw('category_id,count(*) as count'))
->groupBy('category_id')
->get();
In Laravel 8 you can use countBy() to get the total count of a group.
Check the documentation on the same.
https://laravel.com/docs/8.x/collections#method-countBy
Simple solution(tested with Laravel 9 and Spatie/Permissions).
Controller:
//Get permissions group by guard name(3 in my case: web, admin and api)
$permissions = Permission::get()->groupBy('guard_name');
View:
#foreach($permissions as $guard => $perm)
<div class="form-group">
<label for="permission">Permissions ({{ ucfirst($guard) }}) {{ count($perm) }}</label>
<select name="permission[]" id="permission" class="form-control #error('permission') is-invalid #enderror" multiple>
#foreach($perm as $value)
<option value="{{ $value->id }}">{{ $value->name }}</option>
#endforeach
</select>
#error('permission')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
#endforeach
Here is a more Laravel way to handle group by without the need to use raw statements.
$sources = $sources->where('age','>', 31)->groupBy('age');
$output = null;
foreach($sources as $key => $source) {
foreach($source as $item) {
//get each item in the group
}
$output[$key] = $source->count();
}
I am using the NextGen gallery WordPress plugin for a site. In my gallery.php template I want to retrieve the number of images for each gallery displayed in the loop. I cannot figure out a way to get the data and print it under the thumbnail of each gallery that's called in gallery.php
Here is where I want to insert the gallery image count and print it:
<a rel="prettyPhoto" href="<?php echo $image->imageURL ?>"
<?php $image->thumbcode ?>><span>view</span></a> <?php echo $total_images; ?> pictures
Anybody have any tips?
Thanks,
Ian
I used this little hack to get my gallery id from the shortcode I pasted inside my post ([nggallery=1])
<?php
$id = get_the_ID();//Get the id of the specific post (inside the loop)
$string = get_the_content();//You get the whole post content where in the end of it lies your shortcode (for example [nggallery=1])
if(preg_match_all('/=(.*?)\]/s',$string,$match)) {
$finalstring=$match[1][0];
}// get the id only (gets all chars after '=' and before ']')
global $wpdb;
$total_attachments = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggpictures WHERE galleryid=$finalstring" ); // Voila!
?>
Hope my solution can work for you.
This is the code you need to count the images:
$global $wpdb;
$images = intval( $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggpictures") );
$galleries = intval( $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggallery") );
$albums = intval( $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggalbum") );
The answer is you can't.
You can count the keys in the $images variable but it will return the wrong number.
You can retrieve the total number of all the images, or all the galleries which is useless.
You can even use a counter as you cycle through the array to try to count how many images are in your gallery, but you'll still get the wrong number.
You can try to use the global variables tthere by default: images->total, which are empty and undefined and don't even exist in the $images or $current object.
The code displays a ("Picture 3 of 7)" type display. If you use it in the imagebrowser.php template, it works. If you paste this exact same code in the gallery-carousel.php template. It will not work. Now you might think switching to $current->total would work, since it inexplicably does for the rest of the variables when using gallery_carousel, but no, it does not. The answer is you have to pull the info from the database directly.
<?php _e('Picture', 'nggallery') ?> <?php echo $image->number ?> <?php _e('of', 'nggallery')?> <?php echo $image->total ?>
It is a sinister, sinister plugin.
If you can't count the images on a gallery, you can count the tags on html block.
On my theme, I get the gallery ID from an custom field and echo the gallery inside the template. So, it's something like that:
<?php
$myGalleryId = 1; // example
$displayImages = 0; // the number of images you want to display from gallery. 0 = all images
$newnggShortcodes = new NextGEN_Shortcodes;
$htmlGallery = str_get_html($newnggShortcodes->show_gallery( array("id"=>$myGalleryId,"images"=>$displayImages,"template"=>"popular") ));
$countImg = count($htmlGallery->find('img')); // number of total <img> tags inside the gallery
$str = $htmlGallery;
?>
<!-- now the html -->
<div id="myGallery">
<?php echo $str; ?>
</div>
<span>Total images: <?php echo $countImg; ?></span>
Hope it helps.