Laravel 在将数组存储到 Json 数据库字段时获得“数组到字符串转换”

问题描述 投票:0回答:4

我正在尝试将带有选项的数组保存到我的 postgres 数据库的 json 数据字段中。我正在使用 Laravel 5.5,并且使用扩展“dimsav/laravel-translatable”进行翻译。

我的模型问题如下所示: 命名空间应用程序;

use Illuminate\Database\Eloquent\Model;
use Dimsav\Translatable\Translatable;

class Question extends Model
{
    use Translatable;
    public $translatedAttributes = ['options', 'answer'];

    protected $casts = [
        'options' => 'array'
    ];
}

问题翻译模型如下所示:

namespace App;

use Illuminate\Database\Eloquent\Model;

class QuestionTranslation extends Model
{

public $timestamps = false;
public $fillable = ['options', 'answer'];

}

以及 QuestionsController 中的存储操作:

 public function store(Request $request)
{
    $question = new Question();

    $options[1] = "test1";
    $options[2] = "test2";

    $question->answer = 1;
    $question->options = $options;

    $question->save();

}

当我尝试存储该数据时,出现错误:

Illuminate \ Database \ QueryException
Array to string conversion (SQL: insert into "question_translations" ("locale", "answer", "options", "question_id") values (en, 1, test1, 18) returning "id")

当我自己使用

json_encode
来投射 $options 时,我可以毫无问题地存储它。

你知道为什么 Laravel 铸造不起作用吗?也许是因为可翻译的扩展名?

php postgresql laravel-5.5
4个回答
21
投票

可以尝试使用这个:

protected $casts = [
    'options' => 'json',
];

我在 MySQL 上测试了它,但理论上它也应该适用于 postgresql。



0
投票

在你的问题模型中尝试这个

protected $casts = [ 'options' => 'json']


-2
投票

也使用json_encode

public function store(Request $request)
{
    $question = new Question();

    $options[1] = "test1";
    $options[2] = "test2";

    $question->answer = 1;
    $question->options = json_encode($options);//json_encode

    $question->save();

}
© www.soinside.com 2019 - 2024. All rights reserved.