[英]One to many relationship with multiple tables in using Eloquent ORM in Laravel
I have three Models User, Email and Phone and database tables Users, Emails and Phones with the columns mentioned below. 我有三个模型用户,电子邮件和电话以及数据库表用户,电子邮件和电话,以下各列。
User: id, name
Emails: id, user_id, emails
Phones: id, user_id, phones
Right now I am using the following function in User Model to make User relationship with Email and Phone using Eloquent ORM One to Many Relationship 现在,我在用户模型中使用以下功能,使用雄辩的ORM一对多关系使用户与电子邮件和电话建立关系
public function profile(){
$data = array();
$data['emails'] = $this->hasMany('App\Email');
$data['phones'] = $this->hasMany('App\Phone');
return
}
I want to know that it is necessary to use hasMany() method twice or there is any other better way to do this? 我想知道是否有必要两次使用hasMany()方法,或者还有其他更好的方法吗?
You should define the relationships separately: 您应该分别定义关系:
public function emails()
{
return $this->hasMany('App\Email');
}
public function phones()
{
return $this->hasMany('App\Phone');
}
This allows you to query a user like that: 这使您可以查询这样的用户:
$user = User::with('emails')->with('phones')->find($userId);
You can do this that way too: 您也可以通过这种方式执行此操作:
$user = User::find($userId)->load('emails', 'phones');
I think "load's" use is more appropriated in your situation. 我认为“负载”的用法更适合您的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.