Laravel雄辩的隐式JSON转换问题。关联数组强制转换为索引数组

时间:2018-12-26 22:00:26

标签: laravel casting eloquent

我尝试在模型中使用这种铸造:

protected $casts = [
    'thumbnails' => 'array', // also tried 'json' and 'object' 
];

保存时,将放置正确的数据:

$thumbnails = ['small' => 'path1.jpeg', 'medium' => 'path2.jpeg', 'large' => 'path3.jpeg'];
$product->images()->create([
    'path' => $imagePath,
    'thumbnails' => $thumbnails
]);

// Saved content of 'thumbnails' field in DB row:
// {"large": "path1.jpeg", "small": "path2.jpeg", "medium": "path3.jpeg"}

然后我尝试访问此字段,我有:

$image = Image::find(6);
dd($image->thumbnails);
// array:3 [▼
//   0 => "path1.jpeg"
//   1 => "path2.jpeg"
//   2 => "path3.jpeg"
// ]

代替

// array:3 [▼
//   'small' => "path1.jpeg"
//   'medium' => "path2.jpeg"
//   'large' => "path3.jpeg"
// ]

数据库字段类型为json。

1 个答案:

答案 0 :(得分:0)

糟糕,我在模型中添加了一些错误的吸气剂...

/**
 * @return array
 * @throws \Exception
 */
public function getThumbnailsAttribute() : array
{
    return resolve(ImageService::class)->getThumbnailUrls($this);
}