Laravel 5.2: DB:raw in relationship

Asked

Viewed 96 times

0

I need to access the table avaliações and make a calculation to calculate the grade of each product.

I tried that way, but the field nota raised in the DB:raw does not appear when I try to access the view, but I can access the table fields avaliacoes normally.

$produtos = Produto::whereHas('avaliacoes', function($q) {
 $q->select(DB::raw('(CEIL(SUM(qualidade+aparencia+preco) / 3 / COUNT(id))) as nota'));
})->get();

A product can have multiple reviews.

Model evaluations

class Avaliacoes extends Model
{
    protected $fillable = array('cliente_id', 'produto_id', 'aparencia', 'preco', 'qualidade');

    public function produto()
    {
       return $this->belongsTo('App\Produto');
    }
}

Product model

class Produto extends Model
{
    public function avaliacoes()
    {
        return $this->hasMany('App\Avaliacoes');
    }
{

INNER JOIN

$produtos = Produto::join('avaliacoes', 'avaliacoes.produto_id', '=', 'produto.id')
   ->select(DB::raw('(CEIL(SUM(qualidade + aparencia + avaliacoes.preco) / 3 / COUNT(avaliacoes.id))) as nota'), 'produto.*');
  • if you did it wrong. if you did a subquery and what you need may be something else ... !!! explain better what you need to do

  • I am listing all registered products along with the notes of each that are stored in the ratings table.

  • So can I have the two layout of the tables? and how they relate?

  • I put the models in the post.

  • if you can do it in two ways, one is by a method plus an attribute to serialize the other an Inner Join, what you think!

  • I tried with Join, but only list one product. The first one that has any evaluation. I put the code with Join in the question.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.