Average sales ticket using AVG Laravel

Asked

Viewed 37 times

0

I’m trying to calculate the average sales value of a store but I’m facing some problems in calculating the total value of each sale, follow the code

Controller:

$valor_total = PedidoProdutos::with('valor_por_pedido')->get();

Model:

use Illuminate\Database\Eloquent\Model;

class PedidoProdutos extends Model
{
    protected $table = 'pedido_produtos';
    protected $fillable = [
        'pedido_id', 'produto_id', 'valor', 'quantidade'
    ];


    public function pedido()
    {
        return $this->belongsTo(Pedido::class, 'pedido_id', 'id');
    }

    public function valor_por_pedido()
    {
        return $this->selectRaw('pedido_id, SUM(valor * quantidade) as total')
            ->groupBy('pedido_id');
    }

    public function media_de_vendas()
    {
        return $this->valor_por_pedido()->avg('total');
    }

}

Error:

Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()

  • this search your in mysql ta wrong

  • pedido_products. not missing in pedido_id,

  • even leaving only groupBy('pedido_id') continues with the same error

  • Carlos is wrong something, has to put his model completely? because the first code is not has nothing to do with the second? I think ! missing a relationship.

  • whenever you use the 'pedido_products. ' puts it in all the code and better or removes from all

  • ready, I put the full model

  • 1

    Carlos this can’t be: PedidoProdutos::with('valor_por_pedido')->get(); because requested value is a query Builder is not a relation!

  • You can work with Scope! in this case, if you are using the wrong technique !!! I think I think!

  • Yes, I was actually confusing things kkkk, I put the query directly in the same controller and it worked, thanks people...

  • One can create a Scope and call as a method! is a good one! example: https://answall.com/questions/148776/para-que-serve-um-scope-no-laravel/151866#151866

Show 5 more comments
No answers

Browser other questions tagged

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