如何隐藏关联数据CakePhp 3.x中的字段 [英] How to Hide Fields in Associated Data CakePhp 3.x
本文介绍了如何隐藏关联数据CakePhp 3.x中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下表,基本上是两个表连接在一起。当我找到Pops的相关记录时,如何删除_joinData字段?
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);
}
返回的数据
{
"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
}
}
]
}
推荐答案
问题在于水合作用:如果在查询中将其禁用,formatResults似乎不起作用。启用水合作用。
实体(在本例中为 Menu.php
)必须包含一个隐藏的变量
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'];
这篇关于如何隐藏关联数据CakePhp 3.x中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文