问题
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