我正在编写一个应用程序,它需要 2 个使用链接表链接在一起的表,因此总共有 3 个表。
//-------
Users
//------
id,
name,
email,
password
//----
UserAccountType
//----
id,
name,
description
//---
UserAccountLink
//---
id,
user_id,
type_id,
用户可以拥有多种帐户类型(管理员、普通用户、开发人员)...此外,我还设置了外键限制。
唯一的问题是我不明白如何链接这些,我尝试了以下方法:
class User extends Model {
// implementation
public function account_type()
{
$this->hasMany('UserAccountTypeLink', 'id', 'id');
}
}
class UserAccountType extends Model {
// Implementation
}
class UserAccountTypeLink extends Model {
// Implementation
public function user_account()
{
return $this->hasOne('UserAccountType', 'type_id', 'id');
}
}
我的预期输出是,例如,用户 1 返回了“Admin”和“Developer”帐户。但目前,我似乎无法获得所需的输出。对我哪里出错有什么想法吗?
最佳答案
您不需要中间 UserAccountTypeLink 表的模型。查看此处以获取有关如何在 Eloquent 中创建多对多关系的更多信息:http://laravel.com/docs/5.1/eloquent-relationships#many-to-many
关于php - Laravel 5 中的链接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31390715/