lundi 28 juin 2021

How can I retrieve data using Eloquent model without accessing the appended fields' function?

I am using Laravel 5.4.

service.php

$results = Coupon::select(...self::SELECTED_FIELDS)->with('user:id,email');
$results = $results
    ->orderBy('created_at', 'DESC')
    ->limit($limit)
    ->offset($offset)
    ->get()
    // Apparently you need to hide the computed fields manually in Laravel?
    ->each(function($row){
        $row->setHidden(
            'coupons',
            'coupons_count',
            'coupon_ids_string',
            'assigned_coupon_ids',
            'used_coupon_ids'
        );
    });

The model codes:

protected $appends = [
    'coupons',
    'coupons_count',
    'coupon_ids_string',
    'assigned_coupon_ids',
    'used_coupon_ids'
];

function getCouponIDsStringAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}
function getCouponsAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}
function getCouponsCountAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}
function getAssignedCouponIDsAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}
function getUsedCouponIDsAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}

When the codes above executed, the result of $results will execute all the appended fields's function. Output in the browser:

HahahaHahahaHahahaHahahaHahaha

I only want the appended fields to be calculated when I accessed to. I don't need to have the appended fields to be calculated for every time I ask for Coupon . How can I achieve this? Thanks!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3w8hmh3
via IFTTT

Aucun commentaire:

Enregistrer un commentaire