在Laravel迁移和模型中,当我们从数据库中获取JSON格式的字段时,需要使用两次json_decode函数来解析该字段。
以下是一个示例解决方法:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateExampleTable extends Migration
{
public function up()
{
Schema::create('examples', function (Blueprint $table) {
$table->id();
$table->json('data');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('examples');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
use HasFactory;
protected $casts = [
'data' => 'array',
];
public function getDataAttribute($value)
{
return json_decode($value);
}
}
在上述示例中,我们将data
字段的类型设置为array
,这将告诉Laravel将其解析为一个数组。然后,我们定义了一个名为getDataAttribute
的访问器,该访问器将在访问data
属性时自动调用。在该访问器中,我们使用json_decode
函数将JSON字符串解析为PHP数组。
现在,当我们从数据库中获取data
字段时,只需要使用一次访问器即可解析JSON字段:
$example = Example::find(1);
$data = $example->data;
这样,我们就不再需要手动调用json_decode
函数来解析JSON字段了。