如何更新 Laravel Eloquent 列强制转换为集合
P粉741678385
P粉741678385 2024-03-30 09:54:00
0
2
343

我使用的是 Laravel 10。

我通过以下方式利用 JSON 列的转换:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

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

$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();

在这种情况下,似乎只有直接赋值才有效,并且强制转换集合似乎不支持其任何写入功能。

P粉741678385
P粉741678385

全部回复(2)
P粉019353247

尝试将其转换为集合 AsCollection

use Illuminate\Database\Eloquent\Casts\AsCollection;


protected $casts = [
  'meta' => AsCollection::class,
  ...
];
P粉668113768

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

需要使用Illuminate\Database\ Eloquent\Casts\AsCollection 而不是 'collection'

$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
  ];
}
更多信息



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

AsCollection 在 Laravel 8.x 或更高版本中默认可用。 如果您需要旧版本中的集合功能,则需要 自己创建自定义演员表

或者也可以使用 'array'演员:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
  protected $casts = [
    'meta' => 'array', // automatically convert value of 'meta' to array
  ];
}
更多信息
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!