0
votes

I have two models, App\Song (belongsTo App\Host) and App\Host (hasMany App\Song).

In my controller I am using the following query:

$songs = Song::whereHas('host', function($query) {
   $query->eligable()->activeHost();
})->inDownloadedQueue()->get();

This is derived from the following query scopes in my Song.php model public function scopeEligable($query)

{
    $query->where('skip_threshold', '>', \DB::raw('songs.attempts'));
}

public function scopeActiveHost($query)
{
    $query->where('active', 1);
}

public function scopeInDownloadQueue($query)
{
    $query->whereNull('downloaded');
}

This doesn't return any results, turning to ->toSql() function to debug the query is as follows:

select * from "songs" where exists (select * from "hosts" where "songs"."host_id" = "hosts"."id" and "skip_threshold" > songs.attempts and "active" = ?) and "downloaded" is null

This host = ? seems to be the problem. Any ideas why this is?

1

1 Answers

1
votes

The ? is a SQL parameter. Eloquent uses PDO parameterized queries, which helps prevent SQL injection.

The query itself will show active = ?, but when the query is executed, it will bind your value (1) to this parameter, and the query that is actually executed will be active = 1.

The queries are fine, you're just not getting any results because you don't have any songs in your downloaded queue that are related to eligible, active hosts.