我用的是拉威尔10号.

我正在以以下方式利用JSON专栏的强制转换:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
  protected $casts = [
    'meta' => 'collection', // here
  ];
}

当try 直接更新集合中的值时,例如:

$model->meta->put('test', 100);
$model->save();

什么也没发生.

当我按原样分配变量时,它可以正常工作.

$model->meta = ['test' => 100];
$model->save();

但是,如果我只需要更新/添加单个元素怎么办?

我发现了以下解决方法,但这是预期的行为吗?

$meta = $model->meta;
$meta->put('test', 100);
$model->meta = $meta;
$model->save();

似乎只有直接赋值在这种情况下有效,而且CAST集合似乎不支持其任何写入功能.

推荐答案

解决方案(Laravel 8.28或更高版本)

一百零二

$casts数组中,您可以定义各个键的类型.通过指定类型的类(在必要时),Laravel自动处理转换.这就是为什么AsCollection::class的具体用法是必需的.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\AsCollection;

class Item extends Model
{
  protected $casts = [
    'meta' => AsCollection::class, // automatically convert value of 'meta' to Collection::class
  ];
}
More information



解决方案(Laravel 7.x或更低版本)

默认情况下,在Laravel 8.x或更高版本中提供AsCollection.一百零二

或者也可以使用'array' CAST:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
  protected $casts = [
    'meta' => 'array', // automatically convert value of 'meta' to array
  ];
}
More information

Php相关问答推荐

如何在Laravel Controller中存储文本区域值?

PHP -使用preg_match在字符串中进行匹配

Symfony Monolog:使用多个格式化程序

添加自定义Metabox到WooCommerce管理订单,启用HPOS

WooCommerce中仅在单一产品和产品档案页面中将小数设置为大写

在Laravel Eloquent中实现一对多关系

PHP -多维数组到一维数组

将客户重定向到自定义感谢页后的空白页

为什么WooCommerce的动作钩子';woocommerce_checkout_update_order_review';包含旧信息?

curl_close()未从PHP 8开始写入CURLOPT_COOKIEJAR会话文件

用户注册表单中的 HTTP 错误 405

启用 WooCommerce 我的帐户付款方式,允许客户添加付款方式

多个产品类别 Select 自定义 WooCommerce 插件设置页面

如何在 Laravel 迁移中使用日期时间和天数?

Woocommerce 中为空时隐藏显示变体自定义字段数据

避免在 WooCommerce 中多次触发挂钩函数

如何在 WooCommerce 中显示每个自定义选项卡的内容

来自命令行的 PHP 没有给出正确的结果

使用 splat 运算符时按引用传递 (...)

Symfony 自定义注销