laravel-5 - Laravel 将数据从一个模型实例复制到另一个对象(第一个对象的子对象)
问题描述
假设这个 Eloquent 模型:
class User extends Model
{
protected $table = 'users';
}
和这个:
class DeletedUser extends User
{
public function someDeletedUserFunction()
{
// ... some stuff here
}
}
如果我这样做$user = User::find(1)
,$deletedUser = new DeletedUser()
如何将对象内的数据复制$user
到$deletedUser
对象?
我正在尝试使用$deletedUser->attributes = $user->getAttributes
,它很好,但我无法使用原始属性和另一个内部对象数据来做到这一点。
怎样才能做到这一点?
编辑:
由于我使用的示例令人困惑(用户和已删除用户),我将使用另一个示例。假设一个主类汽车。我想构建一个工厂方法 find 以检索汽车子项,它可以是 AutomaticAutomobile 或 ManualAutomobile 对象。因此,如果我调用Automobile::find($id)
该方法,则必须返回 AutomaticAutomobile 或 ManualAutomobile 实例。我要避免的是再次查询数据库,所以我查询获取汽车第一个对象,然后用汽车对象的数据实例化一个子对象。这个例子比以前更清楚吗?
将此代码视为工厂示例:
class AutomobileFactory
{
const MANUAL_AUTOMOBILE= 0;
const AUTOMATIC_AUTOMOBILE= 1;
static function create(int $rewardType, array $data)
{
switch($rewardType){
case self::AUTOMATIC_AUTOMOBILE:
return AutomaticAutomobile::create($data);
break;
case self::MANUAL_AUTOMOBILE:
return ManualAutomobile::create($data);
break;
default:
throw new Exception("Not supported");
}
}
static function find(int $rewardType, int $id) : Reward
{
$automobile = Automobile::find($id);
switch($rewardType){
case self::AUTOMATIC_AUTOMOBILE:
$automatic = someCopyMethods()... // Here I copy all the data
return $automatic;
break;
case self::MANUAL_AUTOMOBILE:
$manual= someCopyMethods()... // Here I copy all the data
return $manual;
break;
default:
throw new Exception("Not supported");
return null;
}
}
}
解决方案
如果 AutomaticAutomobile 和 ManualAutomobile 是汽车的孩子,你为什么不这样做:
static function find(int $rewardType, int $id) : Reward
{
switch($rewardType){
case self::AUTOMATIC_AUTOMOBILE:
$automatic = AutomaticAutomobile::find($id);
return $automatic;
break;
case self::MANUAL_AUTOMOBILE:
$manual= ManualAutomobile::find($id);
return $manual;
break;
default:
throw new Exception("Not supported");
return null;
}
}
推荐阅读
- php - 当 CPU 在低优先级进程中为 100% 时 PHP-FPM 没有响应
- google-chrome - 为什么播放列表.m3u8 / chunklist.m3u8 的请求在停止播放后不断出现?
- r - 修改 %in% 运算符以在列表中查找对象
- visual-c++ - 基本的 hello world 程序无法在 Visual Studio 中构建
- programming-languages - 在设计编程语言时,设计者是否完全指定了它的操作/指称语义?
- swift - TableView 计算错误的estimatedHeightForRowAt
- bash - 使用 AWK 对基于组的列求和
- xtensor - 根据 xtensor 中的位置生成带有元素的张量
- javascript - 数组和对象使用 Redux 和 Immutable.js 导致不必要的重新渲染
- hibernate - 如何在休眠本机 SQL 中处理模式