如何在 Laravel 的数据库中将对象保存为 json?

How to make a job to save an object as json in the database in Laravel?

我正在尝试使用 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);

这是我的模型:

<?PHP

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Rfm extends Model
{
use HasFactory;
protected $fillable = ['RFM'];  
}

迁移:

   public function up()
{
    Schema::create('rfms', function (Blueprint $table) {
        $table->id();
        $table->json('RFM');
        $table->timestamps();
    });
}

现在我向工作人员发出了一个签名命令 运行 但每次它都失败并在日志中显示此错误:

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

我是不是做错了什么?!

JSON 字段接受数组数据类型,但您在传递数组之前将其转换为字符串,

所以只需将 guzzleGet() 的 return 从 return json_encode($aData); 更改为 return $aData;

我同时找到了解决方法:

只是使用查询生成器而不是 eloquent 插入数据,像这样:

public function handle()
{
    $syncedResults = $this->guzzleGet();
    Rfm::truncate();
    
    /**
     * @var \Illuminate\Database\Eloquent\Model $rfm
     */
    DB::table('rfms')->insert(['RFM' => json_encode($syncedResults)]);

}