1

i want to sum in addselect() function but it show me error. I have 2 model as see there:

1.jewelItem model:

protected $table = 'jewel_items';

public function buyInvoice(){
    return $this->belongsTo(BuyInvoice::class,'buy_invoice_id');
}

2.buyInvoice model:

protected $table = 'buy_invoices';

public function jewelsItems(){
return $this->hasMany(JewelsItems::class);
}

and every jewelItem has weight column. my query:

  $buyInvoice=BuyInvoice::addSelect(['allWeight'=>JewelsItem::whereColumn('buy_invoices.id','buy_invoice_id')->sum('weight')
        ])->get();

but it show me this error:

Column not found: 1054 Unknown column 'buy_invoices.id' in 'where clause' (SQL: select sum(`weight`) as aggregate from `jewel_items` where `buy_invoices`.`id` = `buy_invoice_id`)

how can i fix this without using Raw method, cause as here says "Raw statements will be injected into the query as strings" and it's vulnerable.

3 Answers 3

1

In newer version of laravel you can use withSum to get sum of weights for related jewelsItems

$buyInvoice=BuyInvoice::withSum('jewelsItems', 'weight')
                      ->orderBy('jewelsItems_sum_weight')
                      ->get();

Or in older versions you could use withCount for sum as

 $buyInvoice= BuyInvoice::withCount([
                            'jewelsItems as allWeight' => function ($query) {
                                        $query->select(DB::raw("sum(weight)"));
                            }
                    ])->orderBy('allWeight')
                      ->get();
Sign up to request clarification or add additional context in comments.

3 Comments

I got a new error: Call to undefined method App\Models\BuyInvoice::withSum()
@yassin So you are using older version then try the second approach withCount
but my dude. my laravel framwork version is 8.0.0 so is it old? and as i said i don't want to use raw method cause of it's vulnerable
0

you forgot use join in this subquery

JewelsItem::whereColumn('buy_invoices.id','buy_invoice_id')->sum('weight')

Comments

0

Instead of doing a custom count subquery, Laravel has syntaxic sugar for doing this, utilizing the method withSum(). An example of that could be.

$data = Model::query()->withSum('relation.subRelation','weight')->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.