Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Laravel relationship not working #162

Closed
XPOL555 opened this issue Oct 23, 2019 · 3 comments
Closed

Laravel relationship not working #162

XPOL555 opened this issue Oct 23, 2019 · 3 comments

Comments

@XPOL555
Copy link

XPOL555 commented Oct 23, 2019

When Declaring a model with an hasMany

<?php

class Company extends Model{
    /**
     * @Field()
     * @return Address[]|HasMany
     */
    public function addresses():array {
        return $this->hasMany('App\Address');
    }
}

I got this message:

  "message": "Return value of App\\Company::addresses() must be of the type array, object returned",
  "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",

is this intended? I expect to directly query the related model

NB: i'm using v4 dev-master on laravel 6

@moufmouf
Copy link
Member

Hey @XPOL555 ,

What you describe is logic.

$this->hasMany('App\Address'); returns a "HasMany" object that is not "traversable".
When you want to go through your collection, you call "$this->addresses", not "$this->addresses()".

So GraphQLite needs to target the magic property and not the method. Since GraphQLite has no way to target a magic property (I'm working to improve that), you need instead to apply the @field annotation on a getter that wraps the property. So here is what you want to do:

class Company extends Model{
    public function addresses() {
        return $this->hasMany('App\Address');
    }

    /**
     * @Field()
     * @return Address[]
     */
    public function getAddresses():iterable {
        return $this->addresses;
    }

}

Let me know, this should work.

@XPOL555
Copy link
Author

XPOL555 commented Oct 24, 2019

Thank you @moufmouf for the quick reply and... yess! It works like magic! Thank you so much.

I also changed to a belongsToMany with a pivot table and still works.

@XPOL555 XPOL555 closed this as completed Oct 24, 2019
@XPOL555
Copy link
Author

XPOL555 commented Feb 4, 2020

@moufmouf just migrated from dev to v4 and had no issues - great work guys!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants