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

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).

Related

laravel set postgresql identity column in migration

laravel $table->id() will set default nextval('tablename_id_seq'::regclass)
how to set GENERATED BY DEFAULT AS IDENTITY
CREATE TABLE color (
color_id INT GENERATED BY DEFAULT AS IDENTITY,
color_name VARCHAR NOT NULL
);
To quote from the index modifiers table in the current documentation regarding migrations:
->generatedAs($expression)
Create an identity column with specified sequence options (PostgreSQL).
The following code
Schema::create('color', function (Blueprint $table) {
$table->mediumInteger('color_id')->generatedAs();
$table->string('color_name');
});
generates
create table "color" (
"color_id" integer generated by default as identity not null,
"color_name" varchar(255) not null
)
If you add ->nullable() between mediumInteger('color_id') and generatedAs(), the color_id column is instead:
"color_id" integer generated by default as identity null

How to get specific columns from relation table in laravel?

I am trying to fetch soecific columns data from relational table but it is giving me null
$allConsignments = Consignment::query();
$allConsignments->select(['id','customer_reference'])->with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get();
When I don't use select() then it gives correct data .
like this
$allConsignments = Consignment::query();
$allConsignments->with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get()
it is working but I also need specific columns from Consignment Table. what could be the reason?
You can also do like this.
$allConsignments = Consignment::query();
$allConsignments::with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get(['id','customer_reference']);
Actually, I also need to select the foreign key column from the table on which relationship is based. for example in my case I have customer_id in consignment table so it should be like that
$allConsignments = Consignment::query();
$allConsignments->select('id','customer_reference','customer_id')->with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get();
I need to select customer_id as well

Oracle pushing me ORA-00902: invalid datatype

create table accountDetails(
accountNumber int unique,
customerId int unique,
balance int not null,
password varchar(255) not null,
type varchar(255) not null check(type in ('Savings','Current')),
primary key(accountNumber,customerId) )
create table statusDetails(
customerId int references accountDetails(customerId),
primarykey(customerId))
The last table resulted in an error
The last table resulted in an error
ORA-00902: invalid datatype error happens when we try to define a column using an invalid datatype. It's logical really.
Now, you think you haven't declared a column with an invalid datatype, because you think statusdetails table has only one column, customerid. But if you look at your actual statement you follow that column with this:
primarykey(customerId))
Because you mis-typed primary key Oracle treats that line as an attempt to create a second column. Hence the error, because (customerId) is an invalid datatype. So all you need do is pop in the missing space and Oracle will create the table for you.
create table statusDetails(
customerId int references accountDetails(customerId),
primary key(customerId))
You had a compilation error caused by a simple typo. A key skill for a developer is the ability to turn a cool eye on our own code. I urge you to work on acquiring that skill as soon as you can.
Your second table declaration is all wrong. Try this:
CREATE TABLE statusdetails (
customerid INT,
CONSTRAINT fk_cust FOREIGN KEY ( customerid )
REFERENCES accountdetails ( customerid )
)
Note: using "int" data type maps to a NUMBER(38), which may not be what you want. Use the proper oracle data type names.

How to add a constraint to a table with Laravel's migrations?

Let's say I have a table periods with columns start_date and end_date and I want to add a constraint start_date < end_date.
The PostgreSQL query would be:
ALTER TABLE periods ADD CONSTRAINT check_dates CHECK ("start_date" < "end_date");
But I want to do it as a migration with PHP. I guess it will look something like this:
Schema::table('periods', function (Blueprint $table) { $table->something(); });
...but even with IntelliSense I couldn't guess what to write instead of "something()".
I'm not using the newest version of Laravel so it would be nice if you add from which version your code works and what can you do in older versions.
You can run some raw SQL like below as constraints are still not supported by the Blueprint class.
public function up()
{
DB::statement('ALTER TABLE periods ADD CONSTRAINT check_dates CHECK ("start_date" < "end_date")');
}

Add a column, with a default value, to an existing table in oracle

I created a table named- books and have a column in that by the title 'color' . Initially I have null values in the column 'color'. Now, when I run the following query :
alter table books modify color default 'blue';
schema is formed but on doing select *from books , all the values in column color are still null. What would be the correct query to fire?
here is the link:
http://sqlfiddle.com/#!4/f4210/1
Of course. Alter table just changes the table structure but not the content. New entries will get the default.
To update the existing values run a sql-update query like:
update books set color='blue' where colore is null;
If you now inserting into table then only will come with default values. This statement don't know about previous contents of this table. In non technical language, you are telling oracle to do so now on-wards. This statement will not perform check to old values.
alter is ok for the next values to be inserted: try to insert lines without specifying a value for column color, value should be blue.
But this does not work for existing values, for which you just need an update:
update books set color = 'blue';
Hi this query will be used to add column with default value in existing table in oracle.
alter table <table_name> add <column_name> <contraint> default <default_value> not null;
example:
alter table books add record_status number(1,0) default 1 not null;
alter table books add color varchar(20) default 'blue' not null;

Resources