首页  >  问答  >  正文

如何更新 Laravel Eloquent 列强制转换为集合

我使用的是 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粉741678385P粉741678385177 天前341

全部回复(2)我来回复

  • P粉019353247

    P粉0193532472024-03-31 00:48:23

    尝试将其转换为集合 AsCollection

    use Illuminate\Database\Eloquent\Casts\AsCollection;
    
    
    protected $casts = [
      'meta' => AsCollection::class,
      ...
    ];
    

    回复
    0
  • P粉668113768

    P粉6681137682024-03-31 00:03:22

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

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

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

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

    回复
    0
  • 取消回复