对于产品,我想获得有效的优惠券。一次只能有一个有效的优惠券。
我的产品-Modal看起来像这样:
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的应用程序的产品。
从数据库获取数据后,我现在正在做一件非常丑陋的事情:
$product['coupon'] = $product->activeCoupons[0];
我这样做是因为我不想在我的JSON中返回一个activeCoupons数组。我想返回有效的优惠券或null。
有没有更好的方法来做这件事?
发布于 2017-12-13 12:10:41
另一种方法是:
$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);
}
发布于 2017-12-13 13:52:53
这似乎就是你在回复Laerte时所要求的
public function firstActiveCoupon() {
return $this->hasOne('App\Models\Coupon', 'dish_id')
->where('start', '<', new \DateTime())
->where('end', '>', new \DateTime());
}
https://stackoverflow.com/questions/47792296
复制