【问题标题】:Laravel 5.4 Model RelationshipLaravel 5.4 模型关系
【发布时间】:2017-10-25 15:52:03
【问题描述】:

我已经创建了三个表users、courses和user_courses如下图

CREATE TABLE `users` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `address` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `status` enum('0','1') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

    CREATE TABLE `courses` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `title` text,
  `description` text,
  `price` varchar(255) DEFAULT NULL,
  `schedule` varchar(255) DEFAULT NULL,
  `duration` varchar(255) DEFAULT NULL,
  `summary` text,
  `skills` text,
  `mode` enum('0','1') DEFAULT NULL COMMENT '0-Online 1 -Instructor',
  `random_token` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

CREATE TABLE `user_courses` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) DEFAULT NULL,
  `course_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

现在使用这些表,我想绑定关系,例如当我获取用户时,我能够为用户获取课程,当我访问课程时,我希望用户与课程相关联。 请帮助我如何实现它。

【问题讨论】:

标签: laravel model relationship laravel-5.4


【解决方案1】:

第一次修复

首先,修复 user_course 表结构,其中 users 表的 id 为整数,而在 user_id 中的 user_course 中引用为 bigint。

解决方案

首先要做的是在应用程序中创建模型。然后在模型中创建关系并最终使用这些关系。

创建模型

使用命令行

php artisan make:model Course
php artisan make:model UserCourse

您可以根据需要手动创建它们。默认情况下,它们将在命名空间 App 的 app 文件夹中创建。例如,用户模型将是 App/User 等等。

用户模型在 laravel 默认安装中已经存在。

建立关系

在用户模型中添加以下函数

public function courses()
{
  $this->belongsToMany(Course::class, 'user_course');
}

如果您不打算在课程与用户之间建立反向关系,您可以将课程模型留空。以上定义了用户与课程的关系

用法

在控制器中说你可以将其用作

public function someFunctionInController()
{
    $usersWithCourses = \App\User::with('courses')->get()->toArray(); 

    //result of a single user record will look something like this
   /**
   [
      'id' =>  1,
      'name' => 'some name'
      ... //other users table columns
      //the courses will be an array of array content and will be automatically injected
      'courses' => [[  
         'id' => 1 //the course id
         ... //course table columns,
         'pivot' => [
             'user_id' => 1,
             'course_id' => 1
         ]
      ],[
         'id' => 3 //the course id
         ... //course table columns,
         'pivot' => [
             'user_id' => 1,
             'course_id' => 3
         ]
      ]]
   ]
   **/

} 

【讨论】:

    【解决方案2】:

    我已经得到了答案,所以如果它可以帮助任何人,请在此处发布。 这里主要是分配多对多关系。在我的用户模型中,我已经定义了

    public function courses()
        {
            return $this->belongsToMany('App\Course');
        }
    

    课程模型

    public function users()
        {
            return $this->belongsToMany('App\User');
        }
    

    实际上,这取决于您希望如何使用关系。在代码的某些部分中,您将需要 $user->courses 或更可能查询 $course->users 或两者兼而有之。 现在这里 user_course 表将被假定为一个数据透视表。所以在模型中,你可以写成

    public function courses()
    {
        return $this->belongsToMany('App\Course', 'user_courses');
    }
    

    在这里你还可以指定特定数据透视表的字段的实际名称,即 user_courses 表。然后,我们所要做的只是再添加两个参数,首先是当前模型字段,然后添加模型被加入喜欢

    public function courses()
        {
            return $this->belongsToMany('App\Course', 'user_courses','user_id', 'course_id');
        }
    So using the above model relationship you can easily fetch users with all the respective courses by 
    
    
     User::->with('courses')->get();
    

    【讨论】:

      猜你喜欢
      • 2018-01-22
      • 2017-10-04
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 2017-07-16
      相关资源
      最近更新 更多