我正在尝试将一个带有选项的数组保存到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中的存储操作:
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时,我可以毫无问题地存储它。
你知道为什么拉弗尔铸件不起作用吗?也许是因为可翻译的扩展?
发布于 2021-03-02 14:44:16
还可以使用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();
}https://stackoverflow.com/questions/48028315
复制相似问题