2017-12-13 13 views
0

제품의 경우 활성 쿠폰을 얻고 싶습니다. 한 번에 하나의 활성 쿠폰 만있을 수 있습니다.조건에 따라 하나의 관계 항목 만 얻는 정확한 해결책

class Product extends Model 
{ 
    public $table_name = 'products'; 

    protected $hidden = [ 
     'coupons', 
    ]; 

    public function coupons() { 
     return $this->hasMany('App\Models\Coupon', 'dish_id'); 
    } 

    public function activeCoupons() { 
     $instance = $this->hasMany('App\Models\Coupon', 'dish_id'); 
     $instance->getQuery()->where('start', '<', new \DateTime()); 
     $instance->getQuery()->where('end', '>', new \DateTime()); 
     return $instance; 
    } 
} 

가 나는 JSON-API와 응용 프로그램에 제품을 제공하고있다 :

내 제품은 모달는 다음과 같이 보인다.

나는 지금 매우 추악한 일을하고있는 데이터베이스에서 데이터를 가져 오는 후 : 내 JSON에 activeCoupons의 배열을 반환 싶지 않기 때문에

$product['coupon'] = $product->activeCoupons[0]; 

나는이 일을하고있다. 활성 쿠폰 또는 null을 반환하고 싶습니다.

더 좋은 방법이 있나요?

답변

0

이 작업을 수행하는 또 다른 방법은 다음과 같습니다

$product['coupon'] = $product->activeCoupons()->first(); 

심지어 limit를 사용하여. 아이디어는 다음과 같습니다

public function activeCoupons() { 
    return $this->hasMany('App\Models\Coupon', 'dish_id'); 
       ->where('start', '<', new \DateTime()); 
       ->where('end', '>', new \DateTime()) 
       ->limit(1); 
} 
+0

를 라 어트하기 위해 귀하의 회신에서 요구하는 어떤 것 같다, 매우 깨끗하지 무엇 내 생각에는 .. 그리고 두 번째 접근 방식으로 배열을 얻습니다. 배열에서 하나의 항목이지만 여전히 JSON의 배열입니다 ... – rakete

+0

그래서 불행히도 나는 결과로 필요한 것을 이해하지 못합니다. – Laerte

0

이것은 당신은 아직도 그것을 가져 오는 한 후 각 항목을 반복해야 할 첫 번째로

public function firstActiveCoupon() { 
     return $this->hasOne('App\Models\Coupon', 'dish_id') 
     ->where('start', '<', new \DateTime()) 
     ->where('end', '>', new \DateTime()); 
    }