I have a simple one-to-many one-to-many relationship between three models. Adding $withCount to the middle model, when there is a global scope on the bottom model is causing a strange parameter offset within the subselect query.
Model 1 Top Level
namespace App;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
public function bookings()
{
return $this->hasMany('App\Booking');
}
}
Model 2 Middle Level
namespace App;
use Illuminate\Database\Eloquent\Model;
class Booking extends Model
{
protected $withCount = ['extras']; //This is causing the issue
public function extras()
{
return $this->hasMany('App\Extra');
}
}
Model 3 Bottom Level
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class Extra extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('app', function(Builder $builder)
{
$builder->where('app_id', 1);
});
}
}
Query
use App\Event;
$events = Event::withCount([
'bookings' => function($query){
$query->where('status', 'open');
}
])->get();
returns
select `events`.*,
(
select count(*)
from `bookings`
where `events`.`id` = `bookings`.`event_id`
and `status` = '1'
) as `bookings_count`
from `events`
removing the count on App\Booking gives
select `events`.*,
(
select count(*)
from `bookings`
where `events`.`id` = `bookings`.`event_id`
and `status` = 'open'
) as `bookings_count`
from `events`
as expected