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
– Willian
pedido_products. not missing in pedido_id,
– Willian
even leaving only groupBy('pedido_id') continues with the same error
– Carlos Eduardo Silva
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.
– novic
whenever you use the 'pedido_products. ' puts it in all the code and better or removes from all
– Willian
ready, I put the full model
– Carlos Eduardo Silva
Carlos this can’t be:
PedidoProdutos::with('valor_por_pedido')->get();
because requested value is a query Builder is not a relation!– novic
You can work with Scope! in this case, if you are using the wrong technique !!! I think I think!
– novic
Yes, I was actually confusing things kkkk, I put the query directly in the same controller and it worked, thanks people...
– Carlos Eduardo Silva
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
– novic