У меня есть база данных, в которой я хочу заполнить таблицу Topic
. Они сохраняются за Organization
. Имя Topic
является key
. Для каждого Organization
есть несколько Topics
, и иногда можно вставить array
с одинаковыми именами. Чтобы избежать этой ошибки:
Нарушение ограничения целостности: 1062 Повторяющаяся запись
Я использую опцию firstOrCreate
из Eloquent
. Он ищет organization_id
и name
. Если они еще не существуют вместе, он должен вставить запись, иначе он должен пропустить вставку записи.
public function run($organizationId, $topicName)
{
$this->disableForeignKeys();
$topic = Topic::allTenants()
->firstOrCreate([
'organization_id' => $organizationId,
'name' => $topicName,
], [
'description' => 'Not used',
]);
$this->enableForeignKeys();
return $topic->id;
}
Но когда я вставляю Topic
, с неиспользованным organization_id
, это дает мнеошибка в том, что запись уже существует. Но это не так, потому что organization_id
и name
еще не существуют в базе данных. Так почему же это дает мне эту ошибку? Похоже, что он даже не проверяет как organization_id
, так и name
.
. Это схемы для таблицы тем:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class TopicsUniqueFields extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('topics', function (Blueprint $table) {
$table->unique(['organisation_id', 'name']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('topics', function (Blueprint $table) {
$table->dropUnique(['organisation_id', 'name']);
});
}
}
В приведенной выше таблице указаны уникальные поля. для таблицы Темы.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTopicsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('topics', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('organisation_id');
$table->string('name');
$table->text('description')->nullable();
$table->timestamps();
$table->foreign('organisation_id')
->references('id')->on('organisations');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('topics');
}
}