【问题标题】:What is the best way to add dummy data into the "join table" in laravel?将虚拟数据添加到 laravel 中的“连接表”中的最佳方法是什么?
【发布时间】:2020-07-28 22:40:05
【问题描述】:

我有两个具有多对多关系的模型,我确实将它们与具有第三个表的模型连接起来。

将虚拟数据插入第三张表而不会出现 sql 错误以打破有关外键小鸡的约束的最佳方法是什么? 有没有办法使用前两个表中已经存在的相同数据?

我有这两张表:

class CreateLessonsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Lessons', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->string('title', 100);
            $table->text('body');
            $table->timestamps();

            $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('Lessons');
    }
}

第二个:

class CreateTagsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->id();
            $table->string('name', 50);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tags');
    }
}

和“加入”第三张表:

class CreateLessonTagsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('lesson_tags', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('lesson_id');
            $table->unsignedBigInteger('tag_id');


            $table->foreign('lesson_id')->references('id')->on('lessons')->onDelete('cascade');
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('lesson_tags');
    }
}

提前致谢

【问题讨论】:

标签: mysql database laravel dummy-data


【解决方案1】:

简单来说

for($i =0;$i<100 ; $i++)
{
    DB::table('lesson_tags')->insert(
        [
        'lesson_id' => Arr::random(DB::table('Lessons')->pluck('id')->toArray()),
         'tag_id' => Arr::random(DB::table('tags')->pluck('id')->toArray())
         ]
    );
}

【讨论】:

    【解决方案2】:

    你可以像这样使用 eloquent ORM

    首先你需要在标签和课程模型中声明一个关系:

    在标签模型中

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

    在课程模型中

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

    然后你可以在循环中使用它

    $Lesson = new Lesson();
    $Lesson->user_id = ....
    ...
    $Lessons->save();
    
    $tag = new Tag();
    $tag->name ='';
    
    $Lessons->tags()->save($tag)
    

    【讨论】:

      【解决方案3】:

      高效,只需三个查询:

      $lessonIds = Lesson::pluck('id')->toArray();
      $tagIds = Tag::pluck('id')->toArray();
      
      $insert = [];
      
      $relationsAmount = 10;
      
      $now = \Carbon\Carbon::now();
      
      for ($i = 0; $i < $relationsAmount; $i++) {
          $insert[] = [
              'lesson_id' => array_rand($lessonIds),
              'tag_id' => array_rand($tagIds),
              'created_at' => $now,
              'updated_at' => $now,
          ];
      }
      
      \DB::table('lesson_tags')->insert($insert);
      // if you name your pivot table per Eloquent naming convention (which would be 'lesson_tag' in this case), Laravel will do lot of things for you out of the box
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-30
        • 2019-03-14
        • 1970-01-01
        • 2011-03-09
        • 2018-08-10
        • 1970-01-01
        相关资源
        最近更新 更多