I have model of User and Rating . i need to calculate user rating based on what they get from customer rate . how can i do it ? should i make calculation in User model or Rating model ?
To define an accessor, create a getFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the user's first name.
*
* @param string $value
* @return string
*/
public function getStarAttribute($value)
{
return // whatever calculation you need to do. $value will be the value form the DB column.
}
}
Oh wait I just noticed that 4.9 should be 4 in your example? Is that correct? If so change ceil() to floor() :) Personally I would probably prefer to have half stars and round to nearest like this
@sinnbeck can i recap what i understand with you ?
//steps
1. table user must have "star" attribute
2. make a relation between Model User and Model Rating
// User.php
public function ratings()
{
return $this->hasMany(Rating::class);
}
// Rating.php
public function user()
{
return $this->belongsTo(User::class);
}
3. make a function getFooAttribute() and inside it can make calculation
public function getStarAttribute()
{
$ratingAvg = Rating::where('user_id',$this->id)->avg('rating');
return ceil($ratingAvg);
}
4. return ceil($ratingAvg) will define as star in table user .
okay . silly me for small mistake . i try to rate person A , but star doesn't update .
// this logic will fire if person B rate person A
$rating = new Rating ([
'rater_id' => $user_id,
'user_id' => $deal->post->user_id,
'post_id' => $deal->post->id,
'rating' => $request->get('rating'),
'comment' => $request->get('comment')
],201);
table ratings
id | rater_id | user_id | rating | comment |
1 person B person A 2 empty
Slightly offtopic - how did you (or how do people) come across this algorithms ? I can't remember having it at school. But the same principle applies to if you wanted to have quarters - simply round($ratingAvg * 4) / 4 ;
yup .. its like grab rating system ..
passenger will rate driver,
backend will process the new rating based on record in database ( based on what i know about grab )
system will update new star .
Person A rate Person B
System will update and show new rating
@cyprous I think some people just used basic math. 2.4 * 2 would be 4.8 (and rounded 5). This would the be halfed to the correct value. If I had come up with the formula myself I would probably have worked my way backwards (find a number that gives me the correct value if divided/squared etc by another value)
@fareedr Did you notice my change in your code? You code just builds a Rating and fills it with data, but doesnt save it to the database. You can either use create() like i did or save() on the created model :)
my mistake. i already put it "$rating->save();" . but still no change in database for attribute ('star') . but when i console.log star . it appears '2' .