0

I have a Laravel project with some models, relationships and dynamic scopes into models to perform some queries along model relationships. I want to query these models using a GraphQL endpoint using the Lighthouse package. Is there any way to call those dynamic scopes from the GraphQL schema?

I've tried the directive @where(clause: "...") with no success.

This is the scope at the code of my model:

class Solicitud extends Model {

    ...
    public function movimientos()
    {
        return $this->hasMany('App\Movimiento', 'id', 'id_solicitud_movimiento');
    }

    public function scopeConEstado($query, $id_estado)
    {
        $query->whereHas('movimientos', function($q) use ($id_estado) {
            $q->where('id_solicitud_estado', '=', $id_estado);
        })->get();
    }
}

When I run the GraphQL query I get a SQL error that says:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  la sintaxis de entrada no es válida para integer: «id_estado» (SQL: select * from \"solicitud\" where exists (select * from \"solicitud_movimientos\" where \"solicitud\".\"id_solicitud_movimiento\" = \"solicitud_movimientos\".\"id\" and \"id_solicitud_estado\" = id_estado))

However, if I change $id_estado by a simple 1 (for example) in the code, I get the results as expected for any project who has items with id_solicitud_estado = 1, with no error.

When I launch with tinker the query calling the scope, it works.

Solicitud::conEstado(1)->get();

What am I doing wrong? What it happens with the @where(clause:) directive from Lighthouse? Maybe another directive should be used?

Thanks.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
jairochapela
  • 38
  • 1
  • 6
  • What exactly do you want to query with graphql? `movimientos` relation with `conEstado` scope on a `Solicitud` instance? – Uroš Anđelić May 31 '19 at 18:54
  • Yes. Solicitud has a one-to-many relation called movimientos and I defined the conEstado scope to query those movimientos with the same id_solicitud_estado I pass as argument to the scope. – jairochapela Jun 01 '19 at 08:10

1 Answers1

0

Firstly, you should remove ->get() from the scopeConEstado. Scopes should add clauses to the $query, not resolve it. As for your question, I don't think you can add a dynamic scope in your schema definition easily. What you can do is add a @field directive to the field in question, and then you can resolve that field however you want.

Uroš Anđelić
  • 1,134
  • 7
  • 11
  • Thank you very much for your answer. I've removed `->get()` from the scope. Finally I decided to use a [@builder](https://lighthouse-php.com/3.7/api-reference/directives.html#builder) directive, because I want to filter by a value passed as argument. – jairochapela Jun 05 '19 at 10:51