Laravel雄辩的访问者奇怪的问题
说明: 当我在模型访问器中链接where和orWhere以计算相关模型时,我得到了错误的结果,下面是我的查询。计数返回奇怪的结果,而不按调用事件id进行过滤Laravel雄辩的访问者奇怪的问题,laravel,eloquent,Laravel,Eloquent,说明: 当我在模型访问器中链接where和orWhere以计算相关模型时,我得到了错误的结果,下面是我的查询。计数返回奇怪的结果,而不按调用事件id进行过滤 Laravel Version: 5.6.39 PHP Version: 7.1.19 Database Driver & Version: mysql 5.6.43 复制步骤: 下面的查询将返回预期的结果,但是据我所知,如果我没有错,第一个查询将返回相同的结果,因此我认为这是一个潜在的错误 class Event extends
Laravel Version: 5.6.39
PHP Version: 7.1.19
Database Driver & Version: mysql 5.6.43
复制步骤:
下面的查询将返回预期的结果,但是据我所知,如果我没有错,第一个查询将返回相同的结果,因此我认为这是一个潜在的错误
class Event extends Model
{
protected $table = 'events';
public function registrations()
{
return $this->hasMany('App\Components\Event\Models\Registration','event_id','id');
}
public function getSeatsBookedAttribute()
{
return $this->registrations()
->where('reg_status','=','Confirmed')
->orWhere('reg_status','=','Reserved')
->count();
}
}
这是查询转储
这里是我没有显式分组的查询
class Event extends Model
{
public function getSeatsBookedAttribute()
{
return $this->registrations()
->whereIn('reg_status', ['Confirmed', 'Reserved'])
->count();
}
}
class Event extends Model
{
public function getSeatsBookedAttribute()
{
return $this->registrations()
->where(function($query){
$query->where('reg_status','Confirmed')
->orWhere('reg_status','Reserved');
})
->count();
}
}
这是我显式分组时的查询
"select count(*) as aggregate from events_registration where (events_registration.event_id = ? and events_registration.event_id is not null and reg_status = ? or reg_status = ?) and events_registration.deleted_at is null "
发生这种情况的原因是您正在链接
where()
和orWhere()
。您在幕后看不到的是应用于查询的where event\u id=:event\u id
。最终得到的查询如下所示:
从注册中选择*,其中event_id=:event_id和reg_status='confirm'或reg_status='Reserved'
在普通SQL中,您希望将最后2个条件放在括号中。要想有口才,你需要这样做:
return$this->registrations()->where(函数($query){
$query->where('reg\u status','Confirmed')
->或where('reg_status','Reserved');
});
您可以在这些链上链接toSql()
方法以查看差异。注意,在这种情况下,我认为其中()
是语义上正确的做法
然而,雄辩的人可以为你解决这个问题;向下滚动至雄辩关系文档部分的“计算相关模型”:
$posts=App\Event::withCount([
“注册为座位\u预订\u计数”=>函数($query){
$query->where('reg\u status','confirm')
->或where('reg_status','Reserved');
}
])->get();
您是对的,如果我显式地将where语句分组,查询工作正常,或者使用,其中
也解决了问题,在我看来,框架必须通过将我的语句分组来处理这一问题,或者至少在文档中提到这一点作为警告,不是吗。我在github上就此事发表了一篇文章。框架应该如何确定是否/如何对它们进行分组where()->orWhere()
不会将任何内容放入参数中,但您希望where()->where()->orWhere()
将它们放入参数中吗?我认为这不是一个简单的解决办法。如果想法是“检查有多少方法被链接到何处”-正如您在上面的示例中所看到的,开发人员没有编写第一个where()
。看看我的问题,在这两种情况下,我都使用查询转储更新它,将其分组为我自己,而不是分组,
select count(*) as aggregate from events_registration where events_registration.event_id = ? and events_registration.event_id is not null and (reg_status = ? or reg_status = ?) and events_registration.deleted_at is null