0

i have two model

this is my material model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class material extends Model
{
    protected $fillable = ['proposal_id','thickness','width','length','qty','description'];
    public $timestamps = false;
    protected $appends = ['total'];
    public function proposal()
    {
        return $this->belongsTo(proposal::class);
    }
    public function getTotalAttribute()
    {
        return $this->qty * $this->price;
    }
}

this is my proposal model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class proposal extends Model
{
    public function materials()
    {
        return $this->hasMany(material::class);
    }
}

i'm trying to get all proposal with summary from total attribute which is an appended attribute.

This is not working:

\App\proposal::with(['materials'=>function($q){
    $q->sum('total');
    }])
    ->get();

how to do it properly? thank you

1 Answers1

1

The $q->sum('total') part of your code is performing a database query, whilst your total attribute is generated on the model and not in the database.

For a quick solution you could add an appended attribute to the Proposal model which calculates the total of all it's materials. You will want to be careful doing this as you might run into an N+1 issue (https://laravel.com/docs/5.6/eloquent-relationships#eager-loading).

Following on from this you could check if Materials relationship has been loaded first before calculating the total? Inside your model you can check via $this->relationLoaded('materials').

Lastly but more complicated you could write a custom select which uses MySQL (or whatever database you are using) to generate the total during the query.

Hope that helps? Let me know if you want to discuss further.

SlashEquip
  • 126
  • 5