简体   繁体   中英

How to fix ' Trigger Error ' before INSERT in MySQL?

Within companies table we have every registered companies to the app; in that table I have a multiple primary key composed of 'user_id' and 'vat_number' (vat_number no Auto-Increment). Now, what I want to do is to build up a trigger, this trigger has to be executed before INSERT command and it must be able to verify that isn't possible that exist a user_id associated to the same value of new user_id (every user must be exactly associated to only one vat_number. This is the table's structure:

public function up()
{
    Schema::create('companies', function (Blueprint $table) {
        $table->engine = 'MyISAM';


        $table->integer('user_id')->unsigned();
        $table->string(‘vat_number’, 11);
        $table->string('name', 64);
        $table->char(‘phone’, 11);
        $table->string(‘street’, 64);
        $table->integer(‘house_number’);
        $table->string(‘city’, 64);
        $table->string(‘postal_code’, 64);
        $table->string('email', 64)->unique();
        $table->timestamps();

        //FOREIGN KEY
        $table->foreign('user_id')->references('id')->on('users');

        //PRIMARY KEY
        $table->primary(['user_id’,’vat_number’]);
    });

    DB::statement('ALTER TABLE companies MODIFY user_id INTEGER NOT NULL AUTO_INCREMENT');

}


//TRIGGER CODE

public function up()
{
DB::unprepared('
    CREATE TRIGGER beforeCompanyInsert
        BEFORE INSERT ON companies FOR EACH ROW
        BEGIN
            DECLARE msg VARCHAR(255);
            IF new.user_id = user_id THEN
                SIGNAL SQLSTATE “45000” SET MESSAGE_TEXT = “ERROR”;
            END IF;
         END;
');
}

Now, when I was trying to insert the first row whitin companies table (which now is empty) as a result I have this error.

Executing: INSERT INTO Luxury2 . companies ( user_id , vat_number , name , phone , street , house_number , city , postal_code , email ) VALUES ('11', '2132132', '32', '32', '32', '32', '32', '32', '32@32.it');

ERROR 1054: 1054: Unknown column 'user_id' in 'field list' SQL Statement: INSERT INTO Luxury2 . companies ( user_id , vat_number , name , phone , street , house_number , city , postal_code , email ) VALUES ('11', '2132132', '32', '32', '32', '32', '32', '32', '32@32.it')

In triggers, field references without NEW or OLD (unless in the context of a query within the trigger) make little sense.

Instead of: IF new.user_id = user_id THEN , which leaves MySQL asking "user_id of which row?"

Try: IF EXISTS (SELECT * FROM companies WHERE user_id = NEW.user_id) THEN , which tells MySQL "if there is already a row with the new row's tentative user_id"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM