Laravel - 按自定义列查找或失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29212982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - find by custom column or fail
提问by Limon Monte
There's findOrFail()
method which throws 404 if nothing was found, e.g.:
findOrFail()
如果没有找到任何东西,有一个方法会抛出 404,例如:
User::findOrFail(1);
How can I find an entity by custom column or fail, something like this:
如何通过自定义列或失败找到实体,如下所示:
Page::findBySlugOrFail('about');
回答by Alupotha
Try it like this:
像这样尝试:
Page::where('slug', '=', 'about')->firstOrFail();
回答by Buraco
Update:I'm currently using Laravel 6.9.0 and I confirm that @jeff-puckett is right. Where clause works fine. This is how it works on my tinker.
更新:我目前正在使用 Laravel 6.9.0,我确认@jeff-puckett 是正确的。Where 子句工作正常。这就是它在我的修补匠上的工作方式。
>>> \App\Models\User::findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
>>> App\Models\User
id: "123b5545-5adc-4c59-9a27-00d035c1d212",
name: "John",
surname: "Graham",
email: "[email protected]",
email_verified_at: "2020-01-03 16:01:53",
created_at: "2020-01-03 16:01:59",
updated_at: "2020-01-03 16:01:59",
deleted_at: null,
>>> \App\Models\User::where('name', 'Buraco')->findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
>>> Illuminate/Database/Eloquent/ModelNotFoundException with message 'No query results for model [App/Models/User] 123b5545-5adc-4c59-9a27-00d035c1d212'
>>> \App\Models\User::where('name', 'John')->findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
>>> App\Models\User
id: "123b5545-5adc-4c59-9a27-00d035c1d212",
name: "John",
surname: "Graham",
email: "[email protected]",
email_verified_at: "2020-01-03 16:01:53",
created_at: "2020-01-03 16:01:59",
updated_at: "2020-01-03 16:01:59",
deleted_at: null,
Outdated:
It took at least two hours to realize that if you chain firstOrFail() method after where() in Laravel 5.6, it basically tries to retrieve the first record of the table and removes where clauses. So call firstOrFail before where.
过时:
至少花了两个小时才意识到,如果在Laravel 5.6中将 firstOrFail() 方法链接到 where() 之后,它基本上会尝试检索表的第一条记录并删除 where 子句。所以在 where 之前调用 firstOrFail。
Model::firstOrFail()->where('something', $value)