Объединение таблиц базы данных в Laravel контроллере - PullRequest
0 голосов
/ 02 марта 2020

У меня есть две таблицы с отношением «многие ко многим: см. ниже. enter image description here

enter image description here

class CreateThoughtJournalEntryEmotionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('thought_journal_entry_emotions', function (Blueprint $table) {
            $table->integer('thought_journal_entry_id')->unsigned();
            $table->integer('emotion_id')->unsigned();

            $table->foreign('thought_journal_entry_id')
            ->references('id')
            ->on('thought_journal_entries')
            ->onUpdate('cascade')
            ->onDelete('cascade');

            $table->foreign('emotion_id')
            ->references('id')
            ->on('emotions')
            ->onUpdate('cascade')
            ->onDelete('cascade');
        });
    }

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

Я добавил связи для каждой из моделей.

public function emotions() {
    return $this->belongsToMany(Emotion::class,
         'thought_journal_entry_emotions',
         'thought_journal_entry_id',
         'emotion_id');
}
public function thoughtJournalEntries() {
    return $this->belongsToMany(ThoughtJournalEntry::class,
        'thought_journal_entry_emotions',
        'emotion_id',
        'thought_journal_entry_id');
}

Эмоции отбираются с помощью формы, поэтому на данный момент каждая эмоция сохраняется в массиве.

$entry->em_id = $request->has('emotions') ? $request->get('emotions') : [];

Как сохранить выбранный идентификатор emotion_id в новой таблице thought_journal_entry_emotions со связанной thought_journal_entry_id? Вот что у меня есть:

$thoughtJournalEntry = new ThoughtJournalEntry;
$emotions = new Emotions;
$emotions = $request->has('emotions') ? $request->get('emotions') : [];

$emotion1 = $emotions[0];
$emotion2 = $emotions[1];
$emotion3 = $emotions[2];

$thoughtJournalEntry->emotions()->sync([$emotion1->id, $emotion2->id, $emotion3->id]);

$thoughtJournalEntry = ThoughtJournalEntry::with('emotions');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...