andrykel's avatar

Inserting into a JSON column in mysql

I have a table defined that has 2 JSON columns and the rest strings. How do I insert key values from an associative array into the JSON columns using query builder?

0 likes
5 replies
r17x's avatar
r17x
Best Answer
Level 1

your must parse array to json with json_encode php function try this example

$arr_tojson = array(
    'dt' => 1,
    'dt2' => 2, 
);
$arr_tojson = json_encode($arr);

YourModel::create(['jsonColumn' => $arr_tojson]);

CMIIW

2 likes
jekinney's avatar

Json in MySQL needs to be a string. As mentioned above json_encode stringafies a json object.

1 like
andrykel's avatar

I have this as my code :

 $input =Request::except('_token');
       
        $arr_tojson = json_encode($input);

        $arr2_tojson = json_encode($input);
        
       Book::create(['bookAttr'=>$arr_tojson]);
       Book::create(['fields'=>$arr_tojson]);
        
        

        DB::table('book')->insert(

            [              
                     $input
            ]
            );

I ran the code but for the JSON columns 'bookAttr' and 'fields' its showing up as null in my database table. I know the way the database is setup is weird, but that's what I have to work with. So what's happening is I get user input via post and I save it to the database. In the database table there are two json columns bookAttr and fields which stores key:value pairs of the users input.

andrykel's avatar

Here is the schema:

  Schema::create('Book', function (Blueprint $table) {
            $table->increments('bid');
            $table->json('bookAttr')->nullable();
            $table->json('fields')->nullable();
            $table->string('title', 255)->nullable();
            $table->string('codeNum', 255)->nullable();
            $table->string('authorLastName', 255)->nullable();
            $table->string('authorFirstName', 255)->nullable();
            $table->string('illustratorFirstName', 255)->nullable();
            $table->string('illustratorLastName', 255)->nullable();
            $table->string('translatorFirstName', 255)->nullable();
            $table->string('translatorLastName', 255)->nullable();
            $table->string('publisher', 255)->nullable();
            $table->string('copyright', 255)->nullable();
            $table->string('isbn', 255)->nullable();
            $table->string('createdBy',255)->nullable();
            $table->timestamps();
        });
andrykel's avatar

issue fixed. I had to add the following to my model:

protected $table = 'book';

Please or to participate in this conversation.