我有两列,price和offer_price。
当我打电话给$ products->价格时,如果它高于0,我希望它带回offer_price,否则返回价格。
我的模态:
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 : '');
}
}
我试图在这里使用它:
$brands = array();
$prices = array();
$out = '';
foreach ($products as $product) {
$brands[$product->brand->id] = $product->brand->brand;
$prices[] = $product->price;
}
答案 0 :(得分:1)
你走在正确的轨道上。您可以在模型的$attributes
数组成员中找到数据,而不是模型中的不同成员变量。
怎么样:
public function getPriceAttribute()
{
$which = (0 < $this->attributes['offer_price'] ? 'offer_price' : 'price');
return $this->attributes[$which];
}
虽然除了你完全想掩盖&#39;价格&#39;来自通常的Laravel互动。也许是$modal->best_price
?