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

incomplete Relation::morphMap() support #29181

Closed
gandesc opened this issue Jul 16, 2019 · 5 comments
Closed

incomplete Relation::morphMap() support #29181

gandesc opened this issue Jul 16, 2019 · 5 comments

Comments

@gandesc
Copy link

gandesc commented Jul 16, 2019

  • Laravel Version: 5.8.28
  • PHP Version: 7.2.20
  • Database Driver & Version:

Description:

When using polymorphic relationships with custom polymorphic types,
when building queries with hasMorph (whereHasMorph), the custom polymorphic types are not
'translated' to classes in all cases and we get Class 'myCustomPolyType' not found errors.

As far as I can tell, the transformation from types to classes is made here

$type = Relation::getMorphedModel($type) ?? $type;

only when types === '*' and I think it should be performed also when the types are specifically given.

Steps To Reproduce:

  • have models with polymorphic relationships
  • build a query with a whereHasMorph condition, where you specify types, similar to
Relation::morphMap([
    'posts' => 'App\Post',
    'videos' => 'App\Video',
]);

$comments = App\Comment::whereHasMorph(
    'commentable', 
    ['posts'], 
    function (Builder $query) {
        $query->where('title', 'like', 'foo%');
    }
)->get();
@driesvints
Copy link
Member

Ping @staudenmeir

@staudenmeir
Copy link
Contributor

We decided against supporting aliases in $types:

  • If you ever change or remove the morphMap, these whereHasMorph() queries don't work anymore.
  • The callback's second parameter $type always contains the class name. It would be confusing to provide an alias but get a class name.

@aocneanu
Copy link
Contributor

The part I was missing is that the $type is later converted in the correct alias if an alias exists.

In my case I'm extending a package model and rewrite the alias in a local ASP, but I can always do Relation::getMorphedModel($type) and get the correct class from the alias.

Thank you!

@Reund0
Copy link

Reund0 commented Dec 3, 2021

So Is there any solution for this issue? how use custom morph type in WhereHasMorph()?

@staudenmeir
Copy link
Contributor

@Reund0 You pass the class instead of the alias:

App\Comment::whereHasMorph(
    'commentable', 
    Relation::$morphMap['posts'],
    ...
);

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

No branches or pull requests

5 participants