简体   繁体   English

我可以将一个 Eloquent model 投射到另一个上吗?

[英]Can I cast one Eloquent model to another?

In eloquent you can have different models operating on a same table.在 eloquent 中,您可以在同一张桌子上运行不同的模型。 So, is it possible to switch an object from one Model to another in a runtime.那么,是否可以在运行时将 object 从一个 Model 切换到另一个。 Assuming that we have three classes:假设我们有三个类:

Product extends Model
ProductSet extends Product
SimpleProduct extends Product

The difference between ProductSet and a SimpleProduct is column complex which has 'true' in it for a ProductSet and 'false' for a SimpleProduct. ProductSet 和 SimpleProduct 之间的区别在于complex列,其中对于 ProductSet 具有“true”,对于 SimpleProduct 具有“false”。

ProductSet and a SimpleProduct models have Scopes applied to them so that ProductSet::all() will get only sets, and SimpleProduct::all() will get only a simple products. ProductSet 和 SimpleProduct 模型应用了范围,因此ProductSet::all()将仅获得集合,而SimpleProduct::all()将仅获得简单产品。

Parent model however allow us to get both types of products via Product::all() so, is it possible to go through all instances of Product class and switch them to their higher level models at runtime based on a value of property complex ?父 model 但是允许我们通过Product::all()获得这两种类型的产品,所以,是否可以通过 Product class 的所有实例的 go 并在基于属性的运行时complex值的更高级别模型上将它们切换到更高级别的模型?

Since you're already extending the class which holds the same props as the parent.由于您已经在扩展 class ,它拥有与父级相同的道具 You can loop over any product collection and get all the attributes through getAttributes() method and pass to the parent.您可以遍历任何product集合并通过getAttributes()方法获取所有属性并传递给父级。 Because each of your model is extending Eloquent Model which accepts attribute in the constructor and fills its attribute.因为您的每个 model 都在扩展 Eloquent Model ,它接受constructor中的属性并填充其属性。

Following example extends the default User class and converts back to the Parent class以下示例扩展了默认User class 并转换回class

<?php

namespace App;

class Admin extends User {}

Get all Admins and convert them to User获取所有Admins并将其转换为User

$admins = \App\Admin::all();

$users = [];
foreach ($admins as $admin) {
    $users[] = new \App\User($admin->getAttributes());
}
dd(collect($users));

Yes you can do that, Based on the prop you have to create object of that specific class是的,您可以这样做,根据您必须创建特定 class 的 object 的道具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM