doumigu9594 2017-12-29 20:51
浏览 412

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

I'm trying to save an array with options into a json datafield of my postgres database. I'm working with Laravel 5.5 and I'm using the extension "dimsav/laravel-translatable" for translations.

My model Question looks like this: namespace App;

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

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

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

The model QuestionTranslation looks like this:

namespace App;

use Illuminate\Database\Eloquent\Model;

class QuestionTranslation extends Model
{

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

}

And the store action in the QuestionsController:

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

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

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

    $question->save();

}

When I try to store that data I get the error:

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

When I use json_encode to cast $options myself, I can store it without problems.

Do you have any idea, why the laravel casting is not working? Maybe because of the translatable extension?

  • 写回答

2条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器