【问题标题】:Laravel: how to make hasMany relation for rows with highest value and using groupByLaravel:如何为具有最高值的行创建 hasMany 关系并使用 groupBy
【发布时间】:2020-06-05 13:31:58
【问题描述】:

在我的 Laravel 项目中,我有两个模型:OfferOfferPromotion

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 等,但没有任何效果。

我如何做到这一点?

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    终于成功了
    解决方案:

    public function activePromotions(){
            return $this->hasMany(OfferPromotion::class)
                ->select('offer_promotions.*')
                ->leftJoin('offer_promotions as promotions2', function($join){
                    return $join->on('offer_promotions.offer_id', '=', 'promotions2.offer_id')
                        ->on('offer_promotions.type', 'promotions2.type')
                        ->on('offer_promotions.expires_at', '<', 'promotions2.expires_at');
                })
                ->whereNull('promotions2.expires_at')
                ->where('offer_promotions.expires_at', '>', date('Y-m-d H:i:s'));
    }
    

    希望对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2018-09-10
      • 2021-11-06
      • 1970-01-01
      • 2013-07-31
      相关资源
      最近更新 更多