Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

php - How To Eager load a Method in model

I have a product model that has a method that returns the price of a product

public function ProductSeller()
{
    return $this->hasMany('AppProductSeller','product_id')->get();
}

public function price()
{
    $productSellers = $this->ProductSeller();
    foreach ($productSellers as $productSeller){
        $productPrice[]=$productSeller->price;
    }

    if (empty($productPrice) == true || min($productPrice) == '0'){
        $Rprice = 'call for price';
    } else {
        $Rprice = number_format(min($productPrice));
    }

    return $Rprice;
}

The problem is I want to Eager load it and get the price like $product->price but I get AppProduct::price must return a relationship instance.

Anybody can help me with it?

question from:https://stackoverflow.com/questions/65869175/how-to-eager-load-a-method-in-model

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you are trying to achieve can be done via accessor and gladly, you have already gone through half of the steps. Just change the name of your method in model as per Laravel's accessor naming convention like this:

public function ProductSeller()
{
    return $this->hasMany('AppProductSeller','product_id');
}



public function GetPriceAttribute()
{
    $productSellers = $this->ProductSeller;
    foreach ($productSellers as $productSeller){
        $productPrice[]=$productSeller->price;
    }

    if (empty($productPrice) == true || min($productPrice) == '0'){
        $Rprice = 'call for price';
    } else {
    $Rprice = number_format(min($productPrice));
    }

    return $Rprice;
}

Now, you can easily access the method like:

$product->price;

Note: In the model, get() function is removed from the end of the relationship and also, the relationship method is called without adding parenthesis in the GetPriceAttribute() method. This approach worked for me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...