我正在使用 laravel 10 和 eloquent 创建一个 API,我想将从 http 请求读取的对象中的值复制到另一个作为 laravel 实体的对象,我有一个具有很多属性的对象,我想自动复制所有属性到另一个对象,这样我就可以将更改保存到数据库,而无需使用对象中每个属性的 $obj1->name = $request->name 将值从请求复制到模型。
让我解释一下:
我有这门课:
class Usuarios extends Model
{
protected $table = 'usuarios';
protected $primaryKey = 'id';
protected $fillable = [... a lot of properties]
}
我的控制器中有这个方法:
function save(Request $request){
$data = $request->all();
$user = new Usuario($data);
$userFromDB = Usuarios::find($data->id);
// is there a way to do this? I just want to copy properties
// without creating a new object, or is there another way to do this?
// using reflection or something like that? or does laravel have
// any other way to do this without copying each value??
copy_values($user,$userFromDB); //????????????
$userFromDB->save();
}
这可能吗?
谢谢
如果您习惯使用软件包,则可以使用任何 Automapper 软件包。我知道 Mark Gerarts 的 Automapper。
否则,使用序列化从一种类型的对象转换为另一种类型的对象的技术会较慢。
$new_object = unserialize(serialize($source_object))