I am using Laravel Query Builder with insertGetId method.
Migration with trigger. Trigger create new table for every user.
public function up()
{
Schema::create('links_group', function (Blueprint $table) {
$table->increments('id');
$table->integer('users_id');
$table->string('name');
$table->timestamps();
$table->softDeletes();
});
DB::statement("CREATE OR REPLACE FUNCTION links_group_triger() RETURNS trigger AS
$BODY$
DECLARE
temp_users_id INTEGER;
tablenew TEXT;
BEGIN
temp_users_id := NEW.users_id;
tablenew := 'links_group_' || NEW.users_id;
IF NOT EXISTS( SELECT * FROM links_group WHERE users_id = temp_users_id ) THEN
EXECUTE 'CREATE TABLE ' || tablenew || ' ( id SERIAL, PRIMARY KEY (id) ,
CHECK ( users_id = ' || temp_users_id || ' ) ) INHERITS (links_group)';
END IF;
EXECUTE 'INSERT INTO ' || tablenew || ' SELECT(' || TG_RELNAME || ' ' || quote_literal(NEW) || ').* RETURNING id;';
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql;");
DB::statement("CREATE TRIGGER links_group_triger
BEFORE INSERT ON links_group
FOR EACH ROW EXECUTE PROCEDURE links_group_triger();");
}
My problem is when using insertGetId data is inserted but ID not return.
$id_group = DB::table('links_group')->insertGetId($form);
Laravel throw error: ErrorException in PostgresProcessor.php line 20: Undefined offset: 0
Problem is with 'return null' in trigger. If I change to 'return new' I have two same insert. I fix this with code