patchEntity 似乎擦除外键

patchEntity appears to erase foreign keys

情况如下:

我有一个 table,它有一个复合键:

CREATE TABLE records (
  id int(11) NOT NULL,
  pacient_id int(11),
  doctor_id int(11),
  --
  --    bunch of stuff that are null
  --
  PRIMARY KEY (id, pacient_id, doctor_id),
  CONSTRAINT records_ibfk_1 FOREIGN KEY (pacient_id) REFERENCES pacients (id),
  CONSTRAINT records_ibfk_2 FOREIGN KEY (doctor_id) REFERENCES doctors (id)
)

到目前为止一切顺利,问题是当我尝试添加记录时...我收到此错误

Cannot insert row, some of the primary key values are missing. Got (, , ), expecting (id, pacient_id, doctor_id)

所以我转到控制器中的添加方法并开始进行两次调试。一个调试 $this->request->data 和另一个调试 $record 本身(在 patchEntity 之后)是这样的:

public function add()
{
    $record = $this->Records->newEntity();

    if ($this->request->is('post')) {
        $record = $this->Records->patchEntity($record, $this->request->data);
        debug($record);
        debug($this->request->data);die;

此代码是使用 bake 生成的。

调试结果为:

object(App\Model\Entity\Record) {

    'others' => '',
    'staging' => '',
    'surgery' => '',
    'medication' => '',
    'alergy' => '',
    '[new]' => true,
    '[accessible]' => [
        '*' => true
    ],
    '[dirty]' => [
        'others' => true,
        'staging' => true,
        'surgery' => true,
        'medication' => true,
        'alergy' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[repository]' => 'Records'

}

[
    'doctor_id' => '2',
    'pacient_id' => '7',
    'points_unusual_lost_weigh' => '',
    'points_lost_weight' => '',
    'lack_apetite' => '',
    'dm' => '',
    'has' => '',
    'dcv' => '',
    'drenal' => '',
    'others' => '',
    'chemotherapy' => '',
    'radiotherapy' => '',
    'metastasis' => '',
    'staging' => '',
    'surgery' => '',
    'alcoholic' => '',
    'smoker' => '',
    'smoker_date' => [
        'year' => '',
        'month' => '',
        'day' => ''
    ],
    'intestine_habit' => '',
    'medication' => '',
    'alergy' => ''
]

看到了,在patchEntity之后有none_id,但是,真不知道为什么到不了

感谢帮助过的人!

-- 已编辑 --

从 rrd 回答下面的第一个问题:是的!我做到了,它看起来像这样:(这是我的联想)

$this->belongsTo('Pacients', [
    'foreignKey' => 'pacient_id',
    'joinType' => 'INNER'
]);

$this->belongsTo('Doctors', [
    'foreignKey' => 'doctor_id',
    'joinType' => 'INNER'
]);

来自 ndm 的第二个问题:(这是我的 $_accessible 变量)

    protected $_accessible = [
    '*' => true,
    'id' => false,
    'pacient_id' => false,
    'doctor_id' => false,
];

正如假设的那样,主键字段设置为 non-accessible/mass-assignable。

要么修改实体代码并删除pacient_iddoctor_id,要么将它们设置为true,或者使用patchEntity中的accessibleFields选项调用仅覆盖传递的实体实例的行为。

实体的调试输出在仅显示 * 时有点误导,因为这表明所有字段都是可访问的。发生这种情况是因为正在过滤 "empty" 数组条目以便仅显示实际可访问的那些字段,但是当使用 * 时这显然是一个问题,因为异常丢失,所以有看来还有进步空间。