【问题标题】:Insert array into database in Laravel在 Laravel 中将数组插入数据库
【发布时间】:2021-10-27 01:00:33
【问题描述】:

我正在尝试使用以下代码插入一个数组。

$notif = new Notification();
$notif->recipient_id = auth()->user()->id;
$notif->sender_id = auth()->user()->id;
$notif->unread = true;
$notif->content = "Top up voucher {$voucher->id} | $amount dalam proses";
$notif->type = 'topup';
$link[] =  [
        'route_name' => 'topup.detail-confirm',
        'param' => ['param_name' => 'id', 'param_value' => $transaction->id]
];
$notif->link = $link;
$notif->save();

我收到以下错误。

数组到字符串的转换

【问题讨论】:

  • 哪一行?什么确切的错误?
  • $notif->link = $link;
  • 我认为 MySQL 不支持 array 数据类型。因此,您需要先将数组转换为JSON string,然后再将其存储到数据库中。

标签: php mysql arrays laravel


【解决方案1】:

很难说没有更多细节,但我认为最可能的罪魁祸首正是错误告诉你的内容。您正在尝试保存此数组:

$link[] =  [
        'route_name' => 'topup.detail-confirm',
        'param' => ['param_name' => 'id', 'param_value' => $transaction->id]
];

放入非数组字段。

你可以做几件事,但一个简单的快速修复可能是将其编码为字符串,如下所示:

$notif->link = json_encode($link);

如果这样可以保存,那么当您将其拔出时,请记住 json_decode 它。

您可以使用不同的方法来字符串化(和/或 DB 列类型),但以上内容可能会对您有所帮助。

【讨论】:

    【解决方案2】:

    您必须将字符串转换为数组,但不能使用 json_encode,忘记 json_encodejson_decode,除非您使用外部 API...

    要转换它,您只需先阅读documentation,因为它有一个部分专门用于转换任何类型的值...

    所以,你的模型必须是这样的:

    class Notification extends Model
    {
        /**
         * The attributes that should be cast.
         *
         * @var array
         */
        protected $casts = [
            'link' => 'array',
        ];
    }
    

    所以下次你想读link这个字段时,你只需做$this->link并认为它会返回一个array,你不需要做任何事情(但在幕后,它使用json_decode )。

    当你想保存值时,你只需:

    $array = [
        'index1' => 123,
        'index2' => [
            'sub_index1' => true,
            'sub_index2' => '2020-08-27'
        ]
    ];
    
    // Or whatever array you want to save
    
    $model->link = $array;
    

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      • 2020-05-01
      • 2020-07-05
      • 2020-12-31
      • 2020-08-26
      相关资源
      最近更新 更多