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

[Bug]: PersistRelations only works on BelongsTo(Many) relations which are nullable #4277

Open
1 task done
kerwin-wildsea opened this issue Feb 28, 2025 · 2 comments
Open
1 task done
Labels

Comments

@kerwin-wildsea
Copy link

kerwin-wildsea commented Feb 28, 2025

Is the bug applicable and reproducable to the latest version of the package and hasn't it been reported before?

  • Yes, it's still reproducable

What version of Laravel Excel are you using?

3.1.63

What version of Laravel are you using?

11.43.2

What version of PHP are you using?

8.4

Describe your issue

Due to the ->save() call in src/Imports/Persistence/CascadePersistManager.php:44 which happens before the relations are persisted it is not possible to use the PersistRelations interface for relations which are required (NOT NULL).

How can the issue be reproduced?

  1. Create two models with a BelongsTo relation between them
  2. Make the relation ->foreignId(RelatedModel::class)->constrained() (NOT NULL)
  3. Create a ToModel import including $model->setRelation('related', new RelatedModel);
  4. Call import on the importer

What should be the expected behaviour?

I'd expect to either note in the docs that this is a limitation of the interface (a massive one) or that it'd not save the model before persisting the relations.

@patrickbrouwers
Copy link
Member

If you have a look at the test https://github.com/SpartnerNL/Laravel-Excel/blob/3.1/tests/Concerns/ToModelTest.php#L169 , I'm doing BelongsTo differently than your example, have a look if doing it that way makes any difference. (Perhaps the correct example is missing in the docs then - if so, would appreciate a PR to the docs). If not please provide a failing unit test to the ToModelTest.

@kerwin-wildsea
Copy link
Author

kerwin-wildsea commented Mar 3, 2025

@patrickbrouwers Thanks for the response. I tried the method using associate instead of setRelation but it has the same result.

Due to the save() function being called before any relations are persisted, any NOT_NULL FK columns will cause the DB to throw a: Integrity constraint violation: 1048 Column '<col>' cannot be null

In the test, it works because the relation is nullable.

I could provide a test, but it'd require a new model + NOT NULL relation in the tests which would affect other tests as well (if the NOT NULL relation is added on an existing model). How would you approach this? Add two new models with different relation?

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

No branches or pull requests

2 participants