Can I store the value of an array in a database and use it with the where clause in Laravel?

I want to save the type of an array in a database column and select it back, using n_group_code_id between the array ($ gID) to compare as shown below.

CREATE TABLE IF NOT EXISTS `tb_notification` ( `id` int(10) NOT NULL AUTO_INCREMENT, `n_user_id` int(10) NOT NULL, `n_group_code_id` varchar(30) NOT NULL, `n_source_id` int(10) NOT NULL, `n_activity_type` varchar(100) NOT NULL, `n_create_times` datetime NOT NULL, `n_description` varchar(160) NOT NULL, `n_status` int(2) NOT NULL, `url` varchar(200) NOT NULL, `updated_at` datetime NOT NULL, `created_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=542 ; -- -- Dumping data for table `tb_notification` -- INSERT INTO `tb_notification` (`id`, `n_user_id`, `n_group_code_id`, `n_source_id`, `n_activity_type`, `n_create_times`, `n_description`, `n_status`, `url`, `updated_at`, `created_at`) VALUES (535, 66, '[7,11,11,11]', 1, 'Issue Till', '2016-04-25 07:04:54', 'Issue Till', 0, '0', '2016-04-25 07:59:54', '2016-04-25 07:59:54'), (536, 66, '[7,11,11,11]', 1, 'Issue Till', '2016-04-25 08:04:47', 'Issue Till', 0, '0', '2016-04-25 08:15:47', '2016-04-25 08:15:47'), (537, 66, '[7,11,11,11]', 159, 'Transfer till', '2016-04-25 08:04:45', 'Transfer till', 0, '0', '2016-04-25 08:20:45', '2016-04-25 08:20:45'), (538, 66, '[7,11,11,11]', 160, 'Transfer till', '2016-04-25 09:04:04', 'Transfer till', 0, '0', '2016-04-25 09:06:04', '2016-04-25 09:06:04'), (539, 66, '[7,11,11,11]', 1, 'Issue Till', '2016-04-26 07:04:29', 'Issue Till', 0, '0', '2016-04-26 07:35:29', '2016-04-26 07:35:29'), (540, 66, '[7,11,11,11]', 162, 'Issue Till', '2016-04-26 07:04:32', 'Issue Till', 0, '0', '2016-04-26 07:38:32', '2016-04-26 07:38:32'), (541, 69, '[7,11,11,11]', 163, 'return Till', '2016-04-26 08:04:33', 'return Till', 0, '0', '2016-04-26 08:39:33', '2016-04-26 08:39:33'); 

Here is my function:

  public function getNotification($user_id =null, $gId=null) { if(is_array($gId)) { $this->_data = self::select('*') ->join('users', 'users.id', '=', 'n_user_id') ->where('users.id','=', $user_id) ->whereIn('n_group_code_id',$gId) ->get(); if (count($this->_data)) { return $this->_data; } else { return false; } }else { return false; } } 
+5
source share
1 answer

Perhaps, but I would recommend that you not reinvent the wheel and use json in DB and encode your array before saving and decode after loading from the database.

First of all, change the column type from row to json (click the first link to find all the information).

To save data:

 $model = new Model(); .... $model->jsonData = json_encode($array); $model->save(); 

To get data:

 $model = Model::find($id); $array = json_decode($model->jsonData); 

In addition, you can do this automatically with accessories and mutators .

+6
source

Source: https://habr.com/ru/post/1247908/


All Articles