嗨,我在迁移中使用json列,并尝试通过模型将值保存到数据中。这是我的移民,
Schema::create('notifications', function (Blueprint $table) {
$table->increments('id');
$table->json('title');
$table->json('message')->nullable();
$table->timestamps();
});
这是我的模型代码,
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
class Notification extends Model
{
use HasTranslations;
public $translatable = ['title','message'];
protected $fillable = [
'title','message'
];
},
这是我的插入代码,
$notification = new Notification();
$notification_title = [
'en' => 'Request created',
'it' => 'Richiesta creata',
];
$notification_title = json_encode($notification_title);
$notification_message = [
'en' => 'Request created',
'it' => 'Richiesta creata',
];
$notification_message = json_encode($notification_message);
$notification->title = $notification_title;
$notification->message = $notification_message;
$notification->save();
似乎json字段无法正确保存。
答案 0 :(得分:1)
将json_encode()
替换为JSON casts:
class Notification extends Model
{
protected $casts = [
'title' => 'array',
'message' => 'array',
];
}