[英]Wrapping eloquent model to another class causes exceeded nesting
我正在使用 Laravel 5.5。 我编写了一个包装器,它采用 Eloquent model 并将其包装到一个Entity
class 并且每个 Z20F35E630DAF49D8CF4C 都有自己的 F35wrapper。 假设用户有很多产品,一个产品属于一个用户。 包装时,我需要获取用户的产品并将它们传递给产品包装器以将它们包装到产品实体中。 在产品包装器中,我需要让该产品的用户所有者将其包装到用户实体。 再说一遍,在用户包装器中,我需要用户产品。 这会创建一个无限循环。
实体包装器:
abstract class EntityWrapper
{
protected $collection;
protected $entityClass;
public $entity;
public function __construct($collection)
{
$this->collection = $collection;
$this->entity = $this->buildEntity();
}
protected function buildEntity()
{
$tempEntity = new $this->entityClass;
$Entities = collect([]);
foreach ($this->collection as $model) {
$Entities->push($this->makeEntity($tempEntity, $model));
}
return $Entities;
}
abstract protected function makeEntity($entity, $model);
}
用户实体包装器:
class UserEntityWrapper extends EntityWrapper
{
protected $entityClass = UserEntity::class;
protected function makeEntity($userEntity, $model)
{
$userEntity->setId($model->user_id);
$userEntity->setName($model->name);
// set other properties of user entity...
//--------------- relations -----------------
$userEntity->setProducts((new ProductEntityWrapper($model->products))->entity);
return $userEntity;
}
}
产品实体包装器:
class ProductEntityWrapper extends EntityWrapper
{
protected $entityClass = ProductEntity::class;
protected function makeEntity($productEntity, $model)
{
$productEntity->setId($model->product_id);
$productEntity->setName($model->name);
// set other properties of product entity...
//--------------- relations -----------------
$productEntity->setUser((new UserEntityWrapper($model->user))->entity);
return $productEntity;
}
}
用户实体:
class UserEntity
{
private $id;
private $name;
private $products;
//... other properties
public function setProducts($products)
{
$this->products = $products;
}
// other getters and setters...
}
当我想通过调用(new UserEntityWrapper(User::all()))->entity
来获取用户实体时,它会导致无限循环。 那么,如何防止嵌套调用模型之间的关系呢? 感谢任何建议。
最后我找到了解决方案。 正如在每个包装器 class 中一样,我使用动态属性来获取关系集合,除了施加额外的查询之外,这会导致延迟加载。 因此,在将 model 集合传递到每个包装器之前,检索必要的关系 model 并且每个包装器首先使用方法getRelations()
检查关系的存在(返回可用关系的数组)。 如果预期的关系可用,则将关系模型的集合传递到适当的包装器 class 中。
用户实体包装器:
class UserEntityWrapper extends EntityWrapper
{
protected $entityClass = UserEntity::class;
protected function makeEntity($userEntity, $model)
{
$userEntity->setId($model->user_id);
$userEntity->setName($model->name);
// set other properties of user entity...
//--------------- relations -----------------
$relations = $model->getRelations();
$products = $relations['products'] ?? null;
if ($products) {
$userEntity->setProducts((new ProductEntityWrapper($products))->entity);
}
return $userEntity;
}
}
并且,类似的功能用于其他包装器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.