How to Hide Fields in Associated Data CakePhp 3.x

橙三吉。 提交于 2019-12-13 03:06:38

问题


I have the following tables, basically two Tables in join. How can I remove the _joinData fields when I make a find of associated records of Pops?

// PopsTable.php
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('pops');
    $this->setDisplayField('name');
    $this->setPrimaryKey('id');

    $this->belongsToMany('Menus', [
        'targetForeignKey' => 'menu_id',
        'foreignKey' => 'pop_id',
        'joinTable' => 'pop_menus',
    ]); 
}
// MenusTable.php
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('menus');
    $this->setDisplayField('name');
    $this->setPrimaryKey('id');

    $this->belongsTo('Categories', [
        'foreignKey' => 'category_id'
    ]);
    $this->hasMany('MenuDetails', [
        'foreignKey' => 'menu_id'
    ]);
    $this->hasMany('Orders', [
        'foreignKey' => 'menu_id'
    ]);
    $this->belongsToMany('Pops', [
        'targetForeignKey' => 'pop_id',
        'foreignKey' => 'menu_id',
        'joinTable' => 'pop_menus',
    ]);
}
// In PopsController.php

public function getAll() {
    $r = $this->Pops->find('all')
    ->contain(['Menus' => function(Query $q) {
        return $q->select(['name']);
    }])
    ->enableHydration(false)
    ->enableAutoFields(false)         
    ->formatResults(function (\Cake\Collection\CollectionInterface $results) {
        return $results->each(function ($row) {
            foreach ($row['menus'] as $m) {
                unset($m['_joinData']);     // Delete here the _joinData               
            }
        });
    });
    return json_encode($r,true);
  }

Returned Data

 {
    "id": 1,
    "name": "umya Agropoli",
    "city": "Agropoli",
    "radius": 9,
    "capacity": 30,
    "cap": 127,
    "country": "Italy",
    "description": "Negozio anna 0",
    "active": 1,
    "book_hours_open": "1",
    "book_hours_close": "1",
    "menus": [
        {
            "name": "Base C",
            "_joinData": {
                "id": 1,
                "pop_id": 1,
                "menu_id": 2
            }
        }
     ]
   }

回答1:


The problem is with hydration: If it is disabled in the query, formatResults seems to not work. Enabling hydration will work. The Entity (Menu.php in this case) must include an hidden var

 // in Menu.php
 protected $_hidden = ['password', '_joinData'];


来源:https://stackoverflow.com/questions/59118525/how-to-hide-fields-in-associated-data-cakephp-3-x

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!