我有以下表,基本上是两个表连接在一起。找到持久性有机污染物的相关记录时,如何删除_joinData字段?
// 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
}
}
]
}
答案 0 :(得分:0)
问题在于水合作用:如果在查询中将其禁用,formatResults似乎不起作用。启用水合作用。
实体(在这种情况下为Menu.php
)必须包含一个隐藏的变量
// in Menu.php
protected $_hidden = ['password', '_joinData'];