How to create custom relation with Laravel JSON:API

28 Views Asked by At

I recently upgraded from Laravel 5.8 to Laravel 9. I am using cloudcreativity/laravel-json-api version 4.1.0 with Laravel v9.52.16 and PHP 8.2.

Everything works great, except one query. The query used to work in version v1 and was a "hasManyDeep" relation (from staudenmeir/eloquent-has-many-deep), but this seems to be no longer supported in v4.

The relation ship is this: A congress has many talks. There is a many to many relation between talks and speaker. I want all speaker of a congress (associated through talk). The HasManyThrough relation from Laravel Framework does not work here, as there is a many-to-many relation between talks and speakers.

After reading the docs at https://laravel-json-api.readthedocs.io/en/latest/basics/adapters/#eloquent-adapters I believe I need a queriesMany relation. I thought the following will probably do it:

In my Speaker model:

protected function scopeViaCongress(Builder $query, Congress $congress)
{
        return $query
            ->join('speaker_talk', 'speakers.id', '=', 'speaker_talk.speaker_id')
            ->join('talks', 'speaker_talk.talk_id', '=', 'talks.id')
            ->where('talks.congress_id', $congress->id)
            ->distinct();
}

In CongressAdapter:protected function speakers()

{
    return $this->queriesMany(function (Congress $congress) {
        return Speaker::query()->viaCongress($congress);
    });
}

But I get: Call to undefined method Illuminate\Database\Eloquent\Builder::addEagerConstraints()

Any suggestions what I could do to fix this?

0

There are 0 best solutions below