简体   繁体   中英

Add attribute to eloquent model

I would like to calculate the value of an attribute in it's model, but can not get the data I need.

class Product extends Model
{

    protected $appends = ['lowest_price'];

    public function shops(){
        return $this->belongsToMany('App\Shop')->withPivot('price','url');
    }

    public function type(){
        return $this->belongsTo('App\Type');
    }

    public function getLowestPriceAttribute()                      <-----------------------------
    {
        $lowest_price = 0;
        foreach($this->shops() as $shop) {
            if($lowest_price > $shop->pivot->price) {
                $lowest_price = $shop->pivot->price;
            }
        }
        return $lowest_price;
    }
}

$this->shops() does not seem to load all the data I need to do the calculations.

In my view I am able to iterate over the product's shop like so:

@foreach($shops as $shop)   
    <tr>
        <a href="{{ $shop->pivot->url }}" target="_blank">      
            <td>{{ $shop->name }}</td>
            <td>{{ $shop->pivot->price }}EUR</td>
        </a>        
    </tr>
@endforeach

If this is not possible would the best alterrnative be to do the calculations in the view itself instead of the model?

You should be able to do that in an accessor function for sure. I think the problem that you are having is simpler than you think.

$shops in your view is probably a collection, but $this->shops() returns a Query Builder instance.. so try changing this line in the function:

foreach($this->shops() as $shop) {

With this:

foreach($this->shops as $shop) {

And let me know if it works. Without () the shops will be a collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM