Каков наилучший способ добавить фиктивные данные в «таблицу соединений» в laravel? - PullRequest
1 голос
/ 15 апреля 2020

У меня есть две модели со многими отношениями, и я соединил их с моделью с третьей таблицей.

Каков наилучший способ вставить фиктивные данные в третью таблицу без получения 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');
    }
}

Заранее спасибо

Ответы [ 3 ]

0 голосов
/ 16 апреля 2020

Простым способом

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())
         ]
    );
}
0 голосов
/ 16 апреля 2020

Эффективно, только с тремя запросами:

$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
0 голосов
/ 16 апреля 2020

Вы можете использовать красноречивый ORM, как этот

сначала вам нужно объявить отношение в тегах и моделях урока:

в модели тегов

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

в модели урока

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

, затем вы можете использовать это в l oop, например,

$Lesson = new Lesson();
$Lesson->user_id = ....
...
$Lessons->save();

$tag = new Tag();
$tag->name ='';

$Lessons->tags()->save($tag)
...