Lets say I have this column
star
----
1
3
3
1
2
5
3
It has seven rows and there are integer values! I want to have it added and divided by the rows there are.
How do I do it in laravel. I can do it in plain php but I want to learn it in laravel.
Try this :
$avgStar = Model::avg('star');
" Model " will replace with your model name
If you want to do it with the query builder you can use aggregate methods like avg:
$avg_stars = DB::table('your_table')
->avg('star');
Laravel 5 docs about aggregates.
If you have more columns you can use the native function of the database manager using DB::raw
$products = DB::table('products')
->select('id','name',DB::raw('round(AVG(quantity),0) as quantity'))
->groupBy('id','name')
->get();
Table::Where('column', $case)->pluck('column')->avg()
Try this if you need to add multiple conditions:
$avgStar = YourModel::Where(
[
['column_1', '=', $case],
['column_2', '<>', 0]
.....
])->pluck('star')->avg();
// let's say the Model name is Review and Table name is reviews, you have a
'star' column on it
$value = Reviews::all();
$value->avg('star');
return view('page.name')->withValue($value);
// it will calculate an average of star column
Related
i have a query that i want to take some certain amount of object from each category for example 4 from category 1 and 4 from category 2 and here is what i wrote :
$wish = DB::table('table')
->where('category_id', $category)
->whereIn('type_id',[2,4])
->take(8)->get();
so here i want to say to take 4 from type_id 2 and get another 4 from type_id 4 . is there any way to do that or any package to do that in caravel eloquent ??
Give this a try
$wishesByType = DB::table('table')
->where('category_id', $category)
->whereIn('type_id', [2, 4])
->get()
->groupBy('type_id');
$wishes = $wishesByType->map(function ($wish) {
return $wish->take(8)->all();
})->all();
This is not an optimized solution because you are fetching all records and then limiting by each type. Still if you okay with this then this is a quick solution.
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).
Yii2 framework why i cant use this?
$rows = new Query;
$rows->createCommand()
->delete('friends')
->Where(['userid' => 1 ,'userid' => 2])
->orWhere(['userid' => 2 ,'userid' => 1])
->execute();
In the where() and or orWhere() function you are using an hash format (['key'=> 'value'])
Hash Format Hash format is best used to specify multiple
AND-concatenated sub-conditions each being a simple equality
assertion. It is written as an array whose keys are column names and
values the corresponding values that the columns should be.
Lookin to you code This is equivalent to
where userid = 1 and userid = 2
look a this for na useful guide http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
second but most important .. in Yii2 you have delete() and deleteAll()
delete() Deletes the table row corresponding to this active record.
deleteAll() Deletes rows in the table using the provided conditions.
this is working code
$rows->createCommand()->delete('friends',['userid' =>[1,2], 'friendid' =>[1,2])->execute();
Try this
Friends::deleteAll(['and',
[ 'userid'=>3],
['in', 'userid', [1,5,7]]]
);
I am wanting to query 3 seperate tables at once. The main one is Criteria, the two has Many tables, linked by criteria_id are Bedrooms and Properties.
A Criteria can have many Bedrooms and many Properties:
Criteria Model
public function bedrooms()
{
return $this->hasMany('Bedroom');
}
public function properties()
{
return $this->hasMany('Property');
}
I'm unsure if this is possible, but I want to query both of these tables, as well as Criteria to see which criteria has a certain bedroom and a certain property type. Please note, there could be multiple bedrooms and properties stored for each criteria_id.
So far, my query is:
$criterias = Criteria::select('id')
->where('min', '<=', Input::get('single_value'))
->lists('id');
My only logical explanation is -
Get all Criteria where Min <= Value and Criteria.Bedrooms = 1 and
Criteria.Properties = 5.
As if to loop through and see if a criteria has a bedroom / property with that value stored.
Many thanks for your help.
If you are looking for only criteria that meet your constraints, you can use whereHas() on the Bedroom and Property relationships. Then add your where() and lists().
$bedroom_id = '1';
$property_id = '5';
$criteria = Criteria::whereHas('bedrooms', function($q) use ($bedroom_id) {
$q->where('bedroom', $bedroom_id);
})->whereHas('properties', function($q) use ($property_id) {
$q->where('property', $property_id);
})->where('min', '<=', Input::get('single_value'))->lists('id');
Criteria.Bedrooms = 1 and Criteria.Properties = 5 was a little vague, but I added it in where they should go. I'm guessing you actually meant the id of 1 and 5 respectively so it would be getting all criteria that have both a bedroom of id 1 and a property of id 5.
Try Eager Loading the relationships
$criterias = Criteria::with('bedrooms', 'properties')
->where('min', '<=', Input::get('single_value'))
->lists('id');
I'm having issues getting a proper count total with my Laravel model.
Model Structure
User
Item
ItemLike
A user can have multiple Items, and each of these Items can have multiple ItemLikes (when a user 'likes' the item).
I can easily get the individual ItemLike counts when using an Item model:
return $this->itemLikes()->count();
But I can't figure out how to get the total # of ItemLike's a User has across all the Item's he owns.
EXAMPLE
User A has 3 Items. Each Item has 5 ItemLike's, for a grand total of 15.
I tried using eager loading on the User model like this:
return $this->items()->with('itemlikes')->get()->count();
But that returns 3 (the # of Items)
These are the queries it ran, which appears like the second query is the one I want, yet every way I try it I still get 3 instead of 15
select * from `items` where `items`.`user_id` = '1000'
select * from `item_likes` where `item_likes`.`item_id` in ('1000', '1001', '1002')
After suggestions from others I found 2 solutions to get the result.
Using whereIn:
$itemViewCount = ItemView::
whereIn('item_views.item_id', $this->items()->lists('id'))
->count();
return $itemViewCount;
2 queries for a total of 410μs
Using join:
$itemViewCount = $this->items()
->join('item_views', 'item_views.item_id', '=', 'items.id')
->count();
return $itemViewCount;
2 queries for a total of 600μs
Isn't it just a case of creating a method that would return the number of items for the model. e.g.:
#UserModel
public function nbLikes()
{
$nbLikes = 0;
foreach($this->items() as $item) {
$nbLikes += $item->itemLikes()->count();
}
return $nbLikes;
}
And then User::nbLikes() should return the piece of data you are looking for?
try this:
$query="select count(il.id) from item_likes il,item itm where il.item_id=itm.id and tm.user_id=1000";