【问题标题】:Link Tables in Laravel 5Laravel 5 中的链接表
【发布时间】:2015-10-02 03:37:34
【问题描述】:

我正在编写一个应用程序,它需要使用 Link 表将 2 个表链接在一起,因此总共有 3 个表。

//-------
  Users
//------
id,
name,
email,
password

//---- 
UserAccountType
//----
id,
name,
description

//---
UserAccountLink
//---
id,
user_id,
type_id,

用户可以拥有多种帐户类型(Admin、Normal、Developer)...另外,我已经设置了外键限制。

唯一的问题是我不明白如何链接这些,我尝试了以下方法:

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 具有“管理员”帐户和“开发人员”帐户。但目前,我似乎无法获得所需的输出。关于我哪里出错的任何想法?

【问题讨论】:

    标签: php mysql laravel laravel-5 database-migration


    【解决方案1】:

    您不需要中间 UserAccountTypeLink 表的模型。查看此处以获取有关如何在 Eloquent 中创建多对多关系的更多信息:http://laravel.com/docs/5.1/eloquent-relationships#many-to-many

    【讨论】:

    • Table "role_user" 不是和我的链接表一样吗?我会试试这个,谢谢:)
    猜你喜欢
    • 2016-11-17
    • 2015-12-18
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2015-11-07
    • 2015-02-27
    • 2015-04-10
    • 1970-01-01
    相关资源
    最近更新 更多