Laravel hasone 关系解释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47821487/
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 hasone relation explain
提问by Hemant Maurya
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
返回 $this->hasOne('App\Phone', 'foreign_key', 'local_key');
I need hasone relationship in these two tables.
我需要这两个表中的 hasone 关系。
in both tables, the relation should be in between username column in both parent and child table, not id in parent and username or any other in child. Please explain 3rd parameter in above hasone function.
在这两个表中,关系应该在父表和子表中的用户名列之间,而不是父表和用户名中的 id 或子表中的任何其他列。请解释上面 hasone 函数中的第三个参数。
回答by Imran
So, your user has passport, right? Then, in your user Model you need to write the following method to manage this relationship:
那么,您的用户有护照,对吗?然后,在您的用户模型中,您需要编写以下方法来管理此关系:
public function passport(){
return $this->hasOne(Passport::class, 'username', 'username');
}
Here, I think you know about the 1st parameter, It's the model(class) name of the relational table. The 2nd parameter is the foreign key which means the column in passports
table which define the relationship with users
If you don't pass this second argument it will be user_id
by default.
在这里,我想你知道第一个参数,它是关系表的模型(类)名称。第二个参数是外键,这意味着passports
表中定义与关系的列users
如果您不传递第二个参数,它将user_id
默认为。
3rd Parameter
第三个参数
Third parameter is is the column name(local key) of your users
table which is mentioned as a relationship in your passports
table. By If you don't pass the 3rd parameter then by default this is id
. In your case, as you are connecting your users
username with the passports
tables username. So, users
table's username
(3rd parameter) is related to the passports table's
username`(2nd parameter).
第三个参数是表的列名(本地键),它在users
表中被称为关系passports
。By 如果您不传递第三个参数,则默认情况下这是id
. 在您的情况下,因为您将您的users
用户名与passports
表用户名连接起来。因此,users
表的username
(第三个参数)与passports table's
用户名(第二个参数)相关。
回答by Alexey Mezenin
The third parameter is a local key column in the users
table. So the relationship should look like this:
第三个参数是表中的本地键列users
。所以关系应该是这样的:
public function passport()
{
return $this->hasOne('App\Passport', 'username', 'username');
}