【发布时间】:2020-06-05 13:31:58
【问题描述】:
在我的 Laravel 项目中,我有两个模型:Offer 和 OfferPromotion。
OfferPromotion 表示例:
Database table schema of offer_promotions
在 Offer 模型中,我想将 hasMany 关系 称为 "activePromotions"。它必须按类型对促销进行分组,并选择到期日期最长的促销(最后插入的记录)。如果上图中出现,我想得到:
键入突出显示到 2020-02-25
输入首页到 2020-04-11
下面的代码被证明是不正确的,因为它只返回首次优惠的促销活动,其余为空。我认为这是错误地使用 groupBy 的原因。
class Offer extends Model{
(...)
public function activePromotions(){
return $this->hasMany(OfferPromotion::class)
->whereDate('expires_at', '>', date('Y-m-d H:i:s'))
->select(\DB::raw(\DB::getTablePrefix().'offer_promotions.*,
max('.\DB::getTablePrefix().'offer_promotions.expires_at)
as expires_at')
)
->orderBy('expires_at', 'ASC') //display promotions in expiration order
->groupBy('type');
}
}
在我的控制器中,我使用 "with" 语句:
$offers = Offer::MyOffers( $loggedUser->id )
->with(['files', 'activePromotions', 'owner' => function($query){ $query->with('seller');}])
->latest()
->paginate(10);
我搜索并尝试了许多解决方案,但没有一个有效。我尝试了 whereIn 与子查询、joins 等,但没有任何效果。
我如何做到这一点?
【问题讨论】: