Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rmznatly's avatar

Limiting records using attribute

Hi, how can I limit the records in the table using attributes?

    public function getTotalBalanceAttribute()
    {
        return $this->customerAccountTotalBalances->sum('price');
    }

I use this in my CustomerAccount model. This fetches the data in the table columns perfectly. But what I need is to list this value in the table if it is greater than 0. Since there is no column named price in the table of this model, I can't do where to do it directly with the query.

0 likes
6 replies
Sinnbeck's avatar

I hope you are loading the customerAccountTotalBalances. Here you are loading them for each CustomerAccount and doing sum on the result :(

Instead you should make it part of the query (remove the accessor!)

->withSum('customerAccountTotalBalances as total_balance', 'price')

It is now available on ->total_balance

And you can even use it in the query

->having('total_balance', '>', 0)

https://laravel.com/docs/11.x/eloquent-relationships#other-aggregate-functions

1 like
tykus's avatar

Attributes (accessors) are only computed after the Model has been fetched from the database and hydrated, so it cannot be used to limit the query. You will need to write the equivalent SQL to compute the SUM, e.g.

Model::query()
  ->whereHas('customerAccountTotalBalances', function($builder) {
    $builder->selectRaw('SUM(price) as balances')
      ->havingRaw('balances > 0');
  });
1 like
rmznatly's avatar

in table;

->modifyQueryUsing(function (Builder $query, $livewire, $table) {
                $query->whereHas('customerAccountTotalBalances', function ($builder) {
                    $builder->selectRaw('SUM(price) as balances')
                        ->havingRaw('balances > 0');
                });
            })```

or

->query(
                CustomerAccount::query()
                    ->withSum('customerAccountTotalBalances as total_balance', 'price')
                    ->where('total_balance', '>', 0)
            )

Undefined column for these scenarios. where am I going wrong :(

public function customerAccountTotalBalances(): HasMany
    {

        $cashMovements = $this->financeCashMovements();
        $bankMovements = $this->financeBankMovements();
        $bondMovements = $this->financeBondMovements();
        $bondMovementOuts = $this->financeBondMovementOuts();
        $invoices = $this->customerInvoices();


        $movements = $cashMovements      
            ->unionAll($bankMovements)     
            ->unionAll($bondMovements)    
            ->unionAll($bondMovementOuts) 
            ->unionAll($invoices); 

        return $movements->orderBy('created_at', 'asc');
    }
tykus's avatar

@rmznatly what is this relationship??? What are financeXXXXMovements methods?

rmznatly's avatar

@tykus for example;

public function financeCashMovements(): HasMany
    {
        return $this->hasMany(CustomerFinanceCashMovement::class, 'customer_account_id', 'id')
            ->select(
                'id',
                'created_at',
                DB::raw('CASE WHEN movement_type = \'IN\' THEN -price ELSE price END as price'),
                'movement_type',
                'notes',
                DB::raw("'" . CustomerFinanceCashPage::class . "' as movement_model"),
                DB::raw("'CASH' as movement_model_name"),
                DB::raw("CASE WHEN movement_type = 'IN' THEN 'CASH_IN' ELSE 'CASH_OUT' END as movement_name"),
                'movement_number',
                DB::raw("
                    CASE 
                        WHEN movement_type = 'IN' THEN price 
                        ELSE 0 
                    END as price_in
                "),
                DB::raw("
                    CASE 
                        WHEN movement_type = 'OUT' THEN price 
                        ELSE 0 
                    END as price_out
                "),
                'customer_finance_payment_group_id'
            )
            ->orderBy('id', 'asc');
    }

With these relationships, I collect money movements from tables . The final result is the balance.

Could it be that the with methods are not working because I joined the query with union?

tykus's avatar
tykus
Best Answer
Level 104

@rmznatly I don't know the reason for the undefined column error; do you see it when query is being executed, or afterwards?

I don't see the customer_account_id in the selected fields; how is Eloquent meant to associate the records?

What does the full query (as executed) look like?

I honestly would think that creating a view on the database would be preferable to your current approach!

1 like

Please or to participate in this conversation.