How to clear primary key id generator in eloquent/mysql? - laravel-5

In my laravel 5.7 / mysql 5.7 app using eloquent I can clear rows in table using model :
Model::truncate();
But can I to clear primary key id generator, so first row would have value for id=1 ?
Thanks!

Model::truncate() uses 'TRUNCATE' function of MySQL so it resets your 'auto_increment' counter as well.
Read more about 'TRUNCATE' here here
So basically the new insert will start from 1 if the primary key field of the table was made Auto Increment

Related

How can I set index for json column in mysql 8 with laravel migration

I'm creating a project with laravel 6. One of my table column type is json.
The data format in the table column is like this:{age:30, gender:male, nation:china,...}. I am wondering if there is a way for me to set index for this column with laravel migration. my database version is mysql 8.0.21.
thank you!
I found this article very helpful for figuring this out. So for your example structure above, you might have a migration that looks like the following:
public function up(){
Schema::create('my_table', function(Blueprint $table){
$table->bigIncrements('id');
$table->json('my_json_col')->nullable();
$table->timestamps();
// add stored columns with an index
// index in this is optional, but recommended if you will be filtering/sorting on these columns
$table->unsignedInteger('age')->storedAs('JSON_UNQUOTE(my_json_col->>"$.age")')->index();
$table->string('gender')->storedAs('JSON_UNQUOTE(my_json_col->>"$.gender")')->index();
$table->string('nation')->storedAs('JSON_UNQUOTE(my_json_col->>"$.nation")')->index();
});
}
And this is equivalent to the following mysql statement:
create table my_table
(
id bigint unsigned auto_increment primary key,
my_json_col json null,
created_at timestamp null,
updated_at timestamp null,
age int unsigned as (json_unquote(json_unquote(json_extract(`my_json_col`, _utf8mb4'$.age')))) stored,
gender varchar(255) as (json_unquote(json_unquote(json_extract(`my_json_col`, _utf8mb4'$.gender')))) stored,
nation varchar(255) as (json_unquote(json_unquote(json_extract(`my_json_col`, _utf8mb4'$.nation')))) stored
)
collate = utf8mb4_unicode_ci;
create index my_table_age_index
on my_table (age);
create index my_table_gender_index
on my_table (gender);
create index my_table_nation_index
on my_table (nation);
And a simple view of the table after creation:
This example created actual stored columns, which for this scenario i think is what you would want. But you can also make virtual columns, which are created at query time instead of persistent columns, and you would just use the virtualAs function instead of the storedAs function in the migration.
These functions are documented in the Column Modifiers section of the Laravel migration docs, but it doesn't go into detail on JSON columns, this requires a bit more mysql knowledge.
I also found this article helpful for the mysql side of things for the JSON columns (SemiSQL).

getting id of most recent inserted row of table on laravel 5

Suppose I have just inserted row on table test as like Test::create($inputs);,which has auto increment primary key field id.How to get id of row that I have just inserted using laravel 4.2/5 ?
The following snippet:
$test = Test::create($inputs)
Will enable you to use $test->id.
You can get the inserted id by using the example
$inserted_id = Test::create($inputs)->id;
You can use the following line to fetch last insert id while save
after save the record you need to use $test->id;

Find the last record based on a attribute of a table

In laravel, I create a migration table named 'timelogs'. Assumed that, this table have three column id,userid,value. 'id' is primary key and have auto increment property , 'userid' is foreign key. I insert data 1,2,2,2,2 and 3,4,5,6,7 for'userid' and 'value' field respectively.
Now I want to find last inserted record.Such as userid = 2 and value = 7.Here userid field contain different user's id. I want to find specific user's last record. How can I do this without using primary key?
$last_record = DB::table('timelogs')->where('userid', $user_id)->orderBy('id', 'desc')->first();
//var_dump($last_record);

Way to get GORM/Hibernate to work with trigger that sets primary key

I have an existing Oracle database that sets the primary key for an insert via a trigger.
TRIGGER SET_schedtemplate_id_template
BEFORE INSERT
ON schedtemplate
FOR EACH ROW
BEGIN
SELECT schedtemplate_id_template_SEQ.NEXTVAL
INTO :NEW.id_template
FROM DUAL;
END;
We have other applications that depend on this approach for this database
I want to be able to map this database in GORM in my domain object
static mapping = {
autoTimestamp true
table 'schedtemplate'
version false
id column: 'id_template', generator: 'sequence', params: [sequence: 'SCHEDTEMPLATE_ID_TEMPLATE_SEQ']
}
The problem with this approach is that GORM increments the sequence to say 12 but then on insert the sequence gets incremented again to 13. This means other objects in the object graph violate foreign key constraints as they are using GORM's 12 instead of the trigger's 13.
It appears the hibernate setting hibernate.jdbc.use_get_generated_keys = true was developed for this purpose.
How do I configure GORM/Grails to use this setting?
The trigger assigned identity column in Hibernate was discussed here hibernate and DB triggers
Now there is a question, how to configure it in GORM.
Try to use the custom identity generator described above like this :
static mapping = {
...
id column: 'id_template', generator: 'jpl.hibernate.util.TriggerAssignedIdentityGenerator'
}

insert row without set primary column

I have that query :
INSERT INTO GOST (ASSORTMENTID, ROZMIAR, GOST)
VALUES ( 54,'S','MjgwMzktODkgMTc0LTk2')
I want insert new row in table GOST, but I don't want to specify column with primary key - GOSTID. I want that database set next id value.
When I run this code I have that error:
validation error for column GOSTID, value "* null *"
I understand that I should set GOSTID column in INSERT query, yes ?
It is possible to run this without this parameter ?
I think a sample script worths more than 1000 words:
Go to a shell interface in the firebird server machine, cd to a folder where you have read/write permissions, start isql or isql-fb (depends on your system and firebird version) and run this script:
create database 'netmajor.fdb' user 'sysdba' password 'masterkey';
set autoddl off;
create table netmajor_example (
netmajor_id integer not null
, str_data varchar(200)
, int_data integer
, constraint pk_netmajor_example
primary key (netmajor_id)
);
create generator netmajor_gen;
set term ^;
create trigger netmajor_pkassign
for netmajor_example
active before insert position 1
AS
begin
if (new.netmajor_id is null) then
new.netmajor_id = gen_id(netmajor_gen, 1);
end
^
commit work^
set term ; ^
insert into netmajor_example (str_data, int_data) values ('one', 1);
insert into netmajor_example (str_data, int_data) values ('twenty', 20);
commit work;
select * from netmajor_example;
Take a look at the results, which in my machine are:
; NETMAJOR_ID STR_DATA INT_DATA
;============ ============================ ============
; 1 one 1
; 2 twenty 20
IF you have questions, don't hesitate to contact. Best regards.
Obviously, your primary key is a NOT NULL column, which means, it's always required. You cannot insert a row without giving a value for the primary key (unless it were an "auto-number" column which gets automatically set by the database system).
Use "before insert" trigger to set value for primary key. Firebird doesn't have "auto-increment" field type, so you need take care of it by yourself.
See http://www.firebirdfaq.org/faq29/ for tutorial how to do this. Some DB applications (eg Database Workbench) can create the trigger and generator automatically.

Resources