php - Laravel replace property with another if it is 0 -
i have 2 columns, price , offer_price.
when call $products->price, bring offer_price if above 0, if not, return price.
my modal:
class product extends eloquent { protected $table = 'products'; public function type() { return $this->hasone('producttypes', 'id', 'type_id'); } public function brand() { return $this->hasone('productbrands', 'id', 'brand_id'); } public function image() { return $this->hasmany('productimages'); } public function toarray() { $ar = $this->attributes; $ar['type'] = $this->type; $ar['brand'] = $this->spec_brand; $ar['price'] = $this->price; return $ar; } public function getspecbrandattribute() { $brand = $this->brand()->first(); return (isset($brand->brand) ? $brand->brand : ''); } public function getpriceattribute() { $price = $this->price; return (isset($price->price) ? $price->price : ''); } }
i'm trying use here:
$brands = array(); $prices = array(); $out = ''; foreach ($products $product) { $brands[$product->brand->id] = $product->brand->brand; $prices[] = $product->price; }
you're on right track. can find data in $attributes
array member of model, rather distinct member variables in model.
how about:
public function getpriceattribute() { $which = (0 < $this->attributes['offer_price'] ? 'offer_price' : 'price'); return $this->attributes[$which]; }
though recommend name other 'price', unless want mask 'price' usual laravel interaction. perhaps $modal->best_price
?
Comments
Post a Comment