Pergunta

I'm working with Laravel 4.1 and trying to retrieve count information from a pivot table. The name of the pivot is project_subject, which joins projects and subjects together. I use the following inside the Subject model:

public function getUnassignedCount($projectId)
{
    return Subject::project()
      ->wherePivot('project_id', $projectId)
      ->wherePivot('assigned', 0)
      ->count();
}

This returns a query like:

select count(*) as aggregate from projects inner join project_subject on projects.id = project_subject.project_id where project_subject.subject_id is null and project_subject.project_id = '1' and project_subject.assigned = '0'

As can be seen, a null value is automatically inserted for project_subject.subject_id which causes the query to return nothing. Seems odd Laravel would automatically add a column I'm not asking for.

How can I query the pivot table correctly to get the count I want? Short of creating a ProjectSubject model.

Foi útil?

Solução

I used a custom pivot model as posted here: https://github.com/laravel/framework/issues/2093#issuecomment-39154456

Instead of using the above code in my question, I used a call to newPivot like this:

public function getUnassignedSubjectsCount($projectId)
{
    $pivot = Project::newPivot($this, $this->attributes, 'project_subject', true);
    return $pivot->where('project_id', 1)->where('assigned', 0)->count();
}

The above returns what is expected.

Outras dicas

In your where statement the operator value is missing according to Laravel API

public BelongsToMany wherePivot(string $column, string $operator = null, mixed $value = null, string $boolean = 'and')

public function getUnassignedCount($projectId)
{
return Subject::project()
  ->wherePivot('project_id', $projectId)
  ->wherePivot('assigned', '=', 0)
  ->count();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top