database findOrFail Laravel 5 特定字段的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30888527/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 07:56:30  来源:igfitidea点击:

findOrFail Laravel 5 function for specific field

databaselaravelvieweloquent

提问by pavlenko

This is my code:

这是我的代码:

$get_all = Geo_Postal_us::findOrFail($postal);

With this query, Laravel tries to find the idfield in the table.

通过这个查询,Laravel 尝试id在表中查找字段。

I don't have an idfield. I use the postalcolumn as primary key.

我没有id领域。我使用该postal列作为主键。

How do you set the function to find value in postalcolumn and not search from idcolumn?

您如何设置函数以在postal列中查找值而不是从id列中搜索?

Thanks,

谢谢,

回答by James Flight

You could create the behaviour you are looking for with the following:

您可以使用以下内容创建您正在寻找的行为:

Geo_Postal_us::where('postal', $postal)->firstOrFail();

回答by errorinpersona

Laravel by default is searching for the "id" column inside the table if you are using find(). To avoid running into errors here and maybe later, you should always tell laravel that you did take another name for your primary field.

如果您使用 find(),Laravel 默认会在表中搜索“id”列。为了避免在这里或以后遇到错误,你应该总是告诉 laravel 你确实为你的主要字段取了另一个名字。

To do that, in your Geo_Postal_us just edit as the following:

为此,在您的 Geo_Postal_us 中只需编辑如下:

class Geo_Postal_us extends Model
{
      protected $primaryKey = 'postal'; //tell laravel to use 'postal' as primary key field
...
...

I ran into this issue within Voyager and it really drove me nuts :).

我在 Voyager 中遇到了这个问题,这真的让我发疯了 :)。

Hope this helps some people as they google the issue.

希望这可以帮助一些人在谷歌这个问题时。