Laravel eloquent 中的本地键是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26803411/
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
what is local key in laravel eloquent
提问by apache
http://laravel.com/docs/4.2/eloquent#relationships
http://laravel.com/docs/4.2/eloquent#relationships
what does local key mean in this thing? does it mean primary key of the table? or what? for example in this code
本地密钥在这件事中是什么意思?它是表的主键吗?或者是什么?例如在这段代码中
return $this->hasOne('Phone', 'foreign_key');
return $this->hasOne('Phone', 'foreign_key', 'local_key');
回答by zen
local_key
is the primary key of your table. You only need to specify it if your primary key is not called id
.
local_key
是你的表的主键。如果您的主键没有被调用,您只需要指定它id
。
回答by Thomas Dutrion
I believe everything is written in the doc:
我相信一切都写在文档中:
ake note that Eloquent assumes the foreign key of the relationship based on the model name. In this case, Phone model is assumed to use a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method. Furthermore, you may pass a third argument to the method to specify which local column that should be used for the association:
请注意,Eloquent 根据模型名称假定关系的外键。在这种情况下,假设 Phone 模型使用 user_id 外键。如果您希望覆盖此约定,您可以将第二个参数传递给 hasOne 方法。此外,您可以将第三个参数传递给该方法,以指定应用于关联的本地列:
Which basically means that 'local_key' is the name of the table column in your db which is responsible to match the related entity (phone) with your current entity (user).
这基本上意味着'local_key'是您的数据库中表列的名称,它负责将相关实体(电话)与您当前的实体(用户)相匹配。
If you have a look at the db, I'm sure you'll find a table user with a phone_id column, try to change it to something else (like "phone" only) and your eloquent request will crash. Then change your call to return $this->hasOne('Phone', 'user_id', 'phone');
and this might work again.
如果您查看数据库,我相信您会找到一个带有 phone_id 列的表用户,尝试将其更改为其他内容(例如仅“电话”),您的雄辩请求将崩溃。然后将您的呼叫更改为return $this->hasOne('Phone', 'user_id', 'phone');
,这可能会再次起作用。