根据字段值的不同,关联不同的数据表
Laravel 5.8.38
laravel-admin 1.7.6
PHP 版本:7.3.1
活动表(promotion),秒杀活动(p_seckill),拼团活动(p_group)
大概字段如下
promotion
id |type |title
主键|活动类型1秒杀,2拼团|活动名称
1 |1 |秒杀1
2 |2 |拼团
p_seckill
id |p_id |product_id
主键|活动id |参加活动的产品id
1 |1 |20
p_group
id |p_id |limit
主键|活动id|拼团人数
1 |2 |3
活动表和秒杀,拼团表都是一对一关系
model
class Promotion extends Model{
//目前分两个方法创建
public function seckill(){
return $this->hasOne(PSeckill::class,p_id);
}
public function group(){
return $this->hasOne(PGroup::class,p_id);
}
//试过在hasOne()后面加where('promotion.type',1)会报错
}
controller
常规调用是这样
Promotion::query()
->with('seckill')
->with('group')
->get();
试过下面方法会报错
Promotion::query()
->with(['seckill'=>function($q){
$q->where('promotion.type',1);
}])
->with('group')
->get();
使用when不报错,但还是无论type等于多少,都会通时查询seckill和group
Promotion::query()
->when('type=1',function($q){
$q->with('seckill')
})
->when('type=2',function($q){
$q->with('group')
})
->get();
有什么方法, 可以在 type=1只关联seckill, type=2时,只关联group吗
几年前写过一篇文章,来解决这个一模一样的问题
诚然,出现这个问题的原因主要还是在于前期设计存在问题,导致本应很简单的事情变得复杂了起来,更加建议按照 Laravel 中多态的方式,type 使用类名进行表示,这样会更加简单。