亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將雄辯的模型包裝到另一個類會導致嵌套過多

將雄辯的模型包裝到另一個類會導致嵌套過多

PHP
元芳怎么了 2022-12-30 17:03:04
我正在使用 Laravel 5.5。我寫了一個包裝器,它采用 Eloquent 模型并將其包裝到一個Entity類中,每個模型都有自己的包裝器。假設,用戶有很多產品,一個產品屬于一個用戶。包裝時,我需要獲取用戶的產品并將它們傳遞給產品包裝器以將它們包裝到產品實體中。在產品包裝器中,我需要讓該產品的用戶所有者將其包裝到用戶實體。所以,再次,在用戶包裝器中,我需要用戶產品!,這會創建一個無限循環。實體包裝器: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;    }}
查看完整描述

1 回答

?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

最后我找到了解決方案。在每個包裝類中,我使用動態屬性來獲取關系集合,除了強加額外的查詢外,這會導致延遲加載。因此,在將模型集合傳遞給每個包裝器之前,檢索必要的關系模型,每個包裝器首先使用方法getRelations()(返回可用關系數組)檢查關系是否存在。如果預期關系可用,則將關系模型集合傳遞到適當的包裝類中。


用戶實體包裝器:


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;

    }

}

并且,類似的功能用于其他包裝器。


查看完整回答
反對 回復 2022-12-30
  • 1 回答
  • 0 關注
  • 124 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號