[11.x] Add find sole query builder method#54667
Conversation
|
|
Yeah I know, that's why |
|
Sorry, I interpreted your description as suggesting that If you're getting a row by its ID, then by definition, there is already only one... So it's hard to see why I think you may need to provide a clearer example of your specific use-case. |
|
I'm aware that technically this shouldn't make a difference when your primary key column is unique on database level (as it should be). However, I do like the explicit assertion that only a single record is returned instead of silently discarding any potential other records (though theoretically not needed when the primary key is unique). I always use |
I find myself writing
Model::whereKey($id)->sole();a lot in my applications to retrieve a model that I know should exist. ThefindOrFail()method provides similar functionality, but there's no guarantee that only a single record exists in the database since it callsfirst()internally.This pull request introduces a new
findSole()method to retrieve a single model by its key, or throw an exception when no or multiple models match the query. Alternatively,findOrFail()could be updated to behave like this but that would be a breaking change. Personally, I also thinkfindSole()reads nicer when what I want to do is "find a sole model which I know the key of".If you want me to make any changes, clarify anything, or add specific tests, please let me know. 😊