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

fix extended model morph map by checking parent class map #1944

Merged
merged 4 commits into from
Sep 10, 2024

Conversation

wychoong
Copy link
Contributor

@wychoong wychoong commented Sep 9, 2024

currently after model extension, when loading relationship it is unable to retrieve correct morph type

setup

  public function boot(ShippingModifiers $shippingModifiers): void
{
    \Lunar\Facades\ModelManifest::replace(
        \Lunar\Models\Contracts\Product::class,
        \App\Models\Product::class,
    );
}

laravel will be looking for App\Models\Product in the morphMap array but it will not be able to resolve to product since Lunar registered 'product' => 'Lunar\Models\Product

public function morphMap(): void
{
$modelClasses = collect(
Discover::in(__DIR__.'/../Models')
->classes()
->extending(BaseModel::class)
->get()
)->mapWithKeys(
fn ($class) => [
$this->getMorphMapKey($class) => $class::modelClass(),
]
);
Relation::morphMap($modelClasses->toArray());
}
public function getMorphMapKey($className): string
{
$prefix = config('lunar.database.morph_prefix', null);
$key = \Illuminate\Support\Str::snake(class_basename($className));
return "{$prefix}{$key}";
}
}

earlier a workaround would be override the morphMap

Relation::morphMap([
    'product' => \App\Models\Product::class,
]);

this fix resolve this by searching the morphMap array using the Lunar model's FQCN
it also checks if the extended model is already manually registered in morphMap by the user

Copy link

vercel bot commented Sep 9, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
lunar-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 10, 2024 10:20am

@alecritson
Copy link
Collaborator

Thanks @wychoong it seems to do the trick, I added a simple test and also tried to clean the logic on the trait a little. Let me know your thoughts and hopefully we can get this in!

@wychoong
Copy link
Contributor Author

Thanks @wychoong it seems to do the trick, I added a simple test and also tried to clean the logic on the trait a little. Let me know your thoughts and hopefully we can get this in!

looks good to me

@alecritson alecritson merged commit 7670106 into lunarphp:1.x Sep 10, 2024
22 checks passed
@wychoong wychoong deleted the fix/extended-model-morphmap branch September 13, 2024 09:13
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

Successfully merging this pull request may close these issues.

3 participants