【问题标题】:Laravel getting an "Array to string conversion" while storing an Array into a Json database fieldLaravel 在将数组存储到 Json 数据库字段时获得“数组到字符串的转换”
【发布时间】:2018-06-10 05:33:34
【问题描述】:

我正在尝试将带有选项的数组保存到我的 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'
    ];
}

QuestionTranslation 模型如下所示:

namespace App;

use Illuminate\Database\Eloquent\Model;

class QuestionTranslation extends Model
{

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

}

以及 QuestionsController 中的 store 操作:

 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


【解决方案1】:

可以试试这个:

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

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

【讨论】:

    【解决方案2】:
    【解决方案3】:

    也使用 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();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      相关资源
      最近更新 更多