[英]How to make a job to save an object as json in the database in Laravel?
I'm trying to make a job that saves the HTTP response as json in the database using the handle method, this is my code:我正在尝试使用 handle 方法将 HTTP 响应作为 json 保存在数据库中的工作,这是我的代码:
public function handle()
{
$syncedResults = $this->guzzleGet();
Rfm::truncate();
/**
* @var \Illuminate\Database\Eloquent\Model $rfm
*/
Rfm::create(['RFM' => $syncedResults]);
}
public function guzzleGet()
{
$aData = [];
$sCursor = null;
while($aResponse = $this->guzzleGetData($sCursor))
{
if(empty($aResponse['data']))
{
break;
}
else
{
$aData = array_merge($aData, $aResponse['data']);
if(empty($aResponse['meta']['next_cursor']))
{
break;
}
else
{
$sCursor = $aResponse['meta']['next_cursor'];
}
}
}
return json_encode($aData);
here is my model :这是我的模型:
<?PHP
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Rfm extends Model
{
use HasFactory;
protected $fillable = ['RFM'];
}
And the migrations:和迁移:
public function up()
{
Schema::create('rfms', function (Blueprint $table) {
$table->id();
$table->json('RFM');
$table->timestamps();
});
}
now I made a signature command to run the worker but every time it fail with this error in the log:现在我做了一个签名命令来运行工人,但每次它在日志中出现这个错误时失败:
TypeError: Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string given, called in C:\xampp\htdocs\clv\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 920 and defined in C:\xampp\htdocs\clv\vendor\laravel\framework\src\Illuminate\Database\Grammar.php:136
i wonder if I'm doing something wrong?!我想知道我是不是做错了什么?!
i have found a workaround in the meanwhile:与此同时,我找到了一种解决方法:
just inserting the data using the Query Builder instead of eloquent, Like this:只需使用 Query Builder 而不是 eloquent 插入数据,就像这样:
public function handle()
{
$syncedResults = $this->guzzleGet();
Rfm::truncate();
/**
* @var \Illuminate\Database\Eloquent\Model $rfm
*/
DB::table('rfms')->insert(['RFM' => json_encode($syncedResults)]);
}
JSON fields accept array datatype, but you're converting your array into a string before passing it, JSON 字段接受数组数据类型,但您在传递数组之前将其转换为字符串,
So just change the return of guzzleGet()
from return json_encode($aData);
所以只需将guzzleGet()
的返回从return json_encode($aData);
into return $aData;
return $aData;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.