可以将数组值存储在数据库中,并在 Laravel 中使用 where 子句


It is possible to store array value in database and using with where clause in Laravel?

我想将数组类型存储在数据库的列中,并使用在数组($gID)之间比较n_group_code_id的位置将其选中如下功能。

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');

这是我的函数:

 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;
            }
    }

这是可能的,但我建议您不要重新发明轮子并在数据库中使用 json 类型并在保存之前对数组进行编码,并在从数据库加载后对其进行解码。

首先,将列类型从字符串更改为 json(单击第一个链接查找所有信息)。

要保存数据:

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

检索数据:

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

此外,您可以使用访问器和突变器自动执行此操作