【问题标题】:Add the same foreign key to 4 rows Laravel将相同的外键添加到 4 行 Laravel
【发布时间】:2021-08-13 00:08:44
【问题描述】:

我正在使用 Laravel 迁移在 PHPMyAdmin 中创建表。我想做的一件事是有一个问题表和答案表,其中 1 个问题可以有 4 个答案(多项选择)。我想将答案和问题与关系联系起来。

是否可以在 Laravel 中设置主键/外键,以便每次创建新的问题行时,问题连接两个 4 答案(创建时)? 这些行将手动填充,但需要链接。

这可能吗?如果可以,我将不胜感激。

提前谢谢你。

【问题讨论】:

    标签: php sql laravel phpmyadmin relationship


    【解决方案1】:

    是的,这是可能的,方法如下 在答案的文件迁移中,您可以添加unsignedBigInteger(question_id)

    在模型Question你可以添加

    public function answers(){return $this->hasMany(Answer::class)}
    

    在创建答案时,您可以传入与该答案相关的请求question_id

    这是你的要求还是我误解了?

    【讨论】:

      【解决方案2】:

      是的,一种常见的方法是订阅Question 模型的created 事件。有几种方法可以做到这一点,但我通常要么在模型本身中注册 booted() 上的侦听器,要么使用 Observers,如果我有很多事件订阅正在进行并希望它更有条理。

      您可以像这样在模型中注册created 侦听器:

      <?php
      
      namespace App\Models;
      
      use App\Models\Answer;
      use Illuminate\Database\Eloquent\Model;
      use Illuminate\Database\Eloquent\Relations\HasMany;
      
      class Question extends Model
      {
          /**
           * The "booted" method of the model.
           *
           * @return void
           */
          protected static function booted()
          {
              static::created(
                  function ($question)
                      {
                          // This closure will be executed every time 
                          // a new Question instance has been created
                          $question->Answers()->createMany(
                              [
                                  ['sort' => 1],
                                  ['sort' => 2],
                                  ['sort' => 3],
                                  ['sort' => 4],
                              ]
                          );
                      }
              );
          }
      
          /**
           * A Question has many Answers.
           *
           * @return HasMany
           */
          public function Answers(): HasMany
          {
              return $this->hasMany(Answer::class)->orderBy('sort');
          }
      }
      

      在此示例中,我假设您的架构中有一个 sort 列,仅用于演示目的。如果您不想在新的 Answer 实例上预填充任何列,您当然可以只传入空数组 ([])。

      您可以在文档中阅读更多相关信息:https://laravel.com/docs/8.x/eloquent#events

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-13
        • 1970-01-01
        • 2014-05-30
        • 2015-03-10
        • 1970-01-01
        • 2020-04-14
        • 1970-01-01
        • 2014-04-07
        相关资源
        最近更新 更多