Как правильно построить миграцию базы данных? - PullRequest
1 голос
/ 16 октября 2019

Я настраиваю проект laravel (я новичок) для управления клиентами (у клиента много контрактов, а у контракта много разных продуктов). И я хочу реализовать метод CRUD и сгенерировать pdf, но у меня возникла проблема в начале, когда я переносил свою базу данных. (это начало, так что, думаю, мне будет трудно ...)

Я написал все свои миграции (клиент + контракты + продукты) и перенес их клиент (клиенты):

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

    class Clients extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->Increments('id');
            $table->string('name');
            $table->string('company');
            $table->string('email', 50);
            $table->string('phone', 15);
            $table->string('adress1', 50);
            $table->string('adress2', 50);
            $table->string('adresse3', 50);
            $table->string('pays', 20);
            $table->timestamps();
    });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        schema::drop('clients');
    }
}

Контракты (контракты)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Contrats extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contrats', function (Blueprint $table) {
            $table->Increments('id');
           /* $table->unsignedBigInteger('clients_name');
            $table->foreign('name')->references('name')->on('Clients'); */
            $table->string('id_dossier');
            $table->string('id_contrat');
            $table->string('id_bateau');
            $table->date('startdate');
            $table->index('startdate');
            $table->date('enddate');
            $table->index('enddate');
            $table->timestamps();
    });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        schema::drop('contrats');
    }
}

и продукты (продукты)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Produits extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('produits', function (Blueprint $table) {
            $table->Increments('id');
            $table->foreign('name'); 
            $table->string('description', 20);
            $table->double('price');
            $table->double('taxes');
    });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
         schema::drop('produits');
    }
}

Таблица миграции успешно создана. Миграция: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (0,03 секунд) Перенос: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (0,02 секунды) Перенастройка: 2019_10_15_131435_clients мигрировали: 2019_10_15_131435_clients (0.01 сек) Перенастройка: 2019_10_15_131454_contrats

Осветите \ База данных \ QueryException: SQLSTATE [42000]:Синтаксическая ошибка или нарушение прав доступа: 1072 Ключевого столбца «имя» в таблице не существует (SQL: изменить таблицу contrats добавить ограничение contrats_name_foreign ссылки на внешний ключ (name) Clients (name))

в /Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664 660 |// Если при попытке выполнить запрос возникает исключение, мы отформатируем ошибку 661 |// сообщение о включении привязок с SQL, что сделает это исключение 662 |// гораздо полезнее для разработчика, а не только ошибки базы данных. 663 |catch (исключение $ e) {

664 |выбросить новое QueryException (665 | $ query, $ this-> prepareBindings ($ bindings), $ e 666 |);667 |} 668 |

Трассировка исключений:

  1   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'name' doesn't exist in table")
      /Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  2   PDOStatement::execute()
      /Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  Please use the argument -v to see more details.

Я рассчитываю на хорошую миграцию для продолжения этого проекта

Заранее спасибо за вашу помощь,веселит.

Ответы [ 2 ]

0 голосов
/ 16 октября 2019

напишите свою функцию для миграции контраста, как это

Schema::create('contrats', function (Blueprint $table) {
            $table->Increments('id');
            $table->string('id_dossier');
            $table->string('id_contrat');
            $table->string('id_bateau');
            $table->date('startdate')->index();
            $table->date('enddate')->index();
            $table->timestamps();
    });
0 голосов
/ 16 октября 2019

Формат столбца внешнего ключа должен соответствовать формату столбца, на который он ссылается в другой таблице, поэтому вместо unsignedBigInteger он должен быть string

Schema::create('contrats', function (Blueprint $table) {
            $table->Increments('id');
           /* $table->unsignedBigInteger('clients_name'); */
            $table->string('name');
            $table->foreign('name')->references('name')->on('clients');
            $table->string('id_dossier');
            $table->string('id_contrat');
            $table->string('id_bateau');
            $table->date('startdate');
            $table->index('startdate');
            $table->date('enddate');
            $table->index('enddate');
            $table->timestamps();
    });

Поэтому настоятельно рекомендуетсяссылаться на первичный ключ id вместо

Правильный путь

Eloquent будет использовать соглашения об именах для установления правильных отношений с менее явным кодом

clients

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateClientsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('company');
            $table->string('email', 50);
            $table->string('phone', 15);
            $table->string('adress1', 50);
            $table->string('adress2', 50);
            $table->string('adresse3', 50);
            $table->string('pays', 20);
            $table->timestamps();
        });
    }

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

contrats

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContratsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contrats', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('client_id');
            $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
            $table->string('id_dossier');
            $table->string('id_contrat');
            $table->string('id_bateau');
            $table->date('startdate');
            $table->index('startdate');
            $table->date('enddate');
            $table->index('enddate');
            $table->timestamps();
        });
    }

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

produits

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProduitsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('produits', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('client_id');
            $table->foreign('client_id')->references('id')->on('clients');
            $table->string('description', 20);
            $table->double('price');
            $table->timestamps();
        });
    }

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

Надеюсь, это поможет
Bon Courage:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...