2014-11-12 5 views
2

두 개의 열, 가격 및 offer_price가 있습니다.Laravel은 0 일 경우 다른 속성으로 대체합니다.

내가 $ products-> price라고 부를 때 나는 offer_price가 0보다 큰 경우 다시 가져오고 그렇지 않으면 가격을 반환하고 싶습니다.

내 모달 :

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; 
    } 

답변

1

당신이 올바른 궤도에있어. 모델의 별개 멤버 변수가 아닌 $attributes 배열 멤버에서 데이터를 찾을 수 있습니다.

방법에 대해 :

public function getPriceAttribute() 
{ 
    $which = (0 < $this->attributes['offer_price'] ? 'offer_price' : 'price'); 
    return $this->attributes[$which]; 
} 

완전히 일반적인 Laravel 상호 작용에서 '가격'마스크하려는 경우가 아니면 내가, '가격'이 아닌 다른 이름을 추천 할 것입니다 있지만. 아마도 $modal->best_price일까요?

+0

멋진 때 받아 들일 것입니다. :) – imperium2335

+0

고마워! :) – bishop

+0

무슨 뜻인지 확실치 않습니다. offer_price가> 0 인 경우 offer_price에 의해 가격이 항상 오버라이드됩니다. 그렇지 않으면 정상 가격 만 표시됩니다. – imperium2335