首页 > 解决方案 > 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;
        }
    }
}

标签: laravel-5model

解决方案


如果 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;
        }
    }

推荐阅读