【问题标题】:How to make composite/multiple primary key in Laravel >= 5.6?如何在 Laravel >= 5.6 中制作复合/多主键?
【发布时间】:2021-10-30 11:51:21
【问题描述】:

我在用户和课程之间创建了多对多关系。模型和迁移如下。

用户模型:

public function courses()
    {
        return $this->belongsToMany(Course::class)->withTimestamps();
    }

课程模式:

public function users()
    {
        return $this->belongsToMany(User::class, 'course_user', 'course_id', 'user_id')->withTimeStamps();
    }

问题是我找不到像这样在 Laravel 中的迁移文件或数据透视表中实现复合主键的方法,

Schema::create('course_user', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();

        $table->integer('course_id')->unsigned()->index()->primary();
        $table->foreign('course_id')->references('id')->on('courses');

        $table->integer('user_id')->unsigned()->index()->primary();
        $table->foreign('user_id')->references('id')->on('users');
    });

在完成上述编码后,当我调用php artisan migrate:refresh 时,出现一个错误,显示在链接表中执行了多个主键。所以我对这个问题做了一个研究,发现ELOQUENT不支持复合主键,如本论坛所述:link to the forum

还有其他方法可以解决这个问题吗? 我设法编写了一段代码来检测数据透视表中的现有条目或控制器内部的多对多关系,并避免新的重复条目。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    为了解决这个问题,我在控制器中编写了一段代码来检测数据透视表中的现有元组,如下所示。注意:我已经使用Resources 检索数据,您可以避免使用资源函数并使用正常方法。

    userIdcourseId 在请求中作为参数传递:

    public function index(Request $request) {
            $target = new AcademicPaymentResource(User::with('courses')->findOrFail($request['userId']));
            if ($target != null) 
            {
                foreach ($target as $query){
                    // search for existing tuples
                    foreach ($query->courses as $subQuery => $key){
                        // Check if courseId in existing tuple is equal to the courseId of request
                        if ( $query->courses[$subQuery]->pivot->course_id == $request['courseId']){
                            
                            // Do anything here..
                            // display data to test if it works
                            return $query->courses[$subQuery];
                        }
                        
                    }
    
                    // update the pivot table if the tuple doesnt exist
                    $user = User::findOrFail($request['userId']);
                    $user->courses()->attach($request['courseId']);
                    
                    // read tuple data again to display if it works
                    $target = new AcademicPaymentResource(User::with('courses')->findOrFail($request['userId']));
                    return $target;
                }
            }
        }
    

    这种方法实际上效果很好,因为到目前为止我已经完美地使用了它。 但是如果有其他合适的方法请不要犹豫回答..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-22
      • 2019-07-07
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多