CI4中DateTime对象无法转字符串,Twilio API数据插MySQL失败求助
解决Twilio DateTime对象插入MySQL的类型转换问题
从Twilio对话参与者接口获取的数据中,dateCreated和dateUpdated是已实例化的DateTime对象,直接将其插入MySQL时会抛出「Object of class DateTime could not be converted to string」错误。尝试修改数据库字段类型为date、datetime、text或varchar均无效,另外尝试用new \DateTime($record->dateCreated)转换时,会触发「DateTime::__construct() expects parameter 1 to be string, object given」错误。
解决思路
直接调用DateTime对象的format()方法,将其转为MySQL支持的datetime格式字符串(如Y-m-d H:i:s),无需重复实例化DateTime对象。
修改后的代码示例
$sql=[ "id_conversation"=>$conversation_id, "identity"=>$record->identity, "identity_proxy_address"=>$explode_whatsapp[1], "date_created"=>$record->dateCreated->format('Y-m-d H:i:s'), "date_updated"=>$record->dateUpdated->format('Y-m-d H:i:s'), ]; $builder->insert($sql);
说明
Twilio返回的dateCreated和dateUpdated本身就是DateTime实例,不需要再用new \DateTime()重新构造。调用format()方法生成符合MySQL要求的字符串格式后,将数据库对应字段类型设置为datetime(或timestamp)即可正常插入。
内容的提问来源于stack exchange,提问作者Luis Lara
相关产品推荐
相关产品推荐

