Skip to content

Commit

Permalink
Added price relation & updated accessor to use it - allows eager loading
Browse files Browse the repository at this point in the history
  • Loading branch information
voidgraphics committed Jan 18, 2022
1 parent ac54dd7 commit bdc3f09
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions src/HasPrices.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Whitecube\LaravelPrices;

use DateTime;
use Whitecube\Price\Price as PhpPrice;
use Illuminate\Database\Eloquent\Model;
use Whitecube\LaravelPrices\Models\Price;

Expand All @@ -19,6 +18,26 @@ public function prices()
return $this->morphMany(Price::class, 'priceable');
}

/**
* The current price model
*
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
*/
public function price()
{
return $this->morphOne(Price::class, 'priceable')->where('type', 'selling')->current();
}

/**
* Easy accessor to get the current price as a whitecube/php-prices object
*
* @return \Whitecube\Price\Price|null
*/
public function getPriceAttribute()
{
return $this->price()->first()?->toObject();
}

/**
* Set (attach) a new price to this item
*
Expand Down Expand Up @@ -54,16 +73,4 @@ public function setPrice(

return $this;
}

/**
* Easy accessor to get the current price
*
* @return \Whitecube\Price\Price|null
*/
public function getPriceAttribute(): ?PhpPrice
{
$model = $this->prices()->current()->first();

return $model?->toObject();
}
}

0 comments on commit bdc3f09

Please sign in to comment.