保存 hasOne 关联的 id

Saving id of hasOne association

我有一个 table 看起来像这样:

,====,==============,============,==========,
| id | contact_from | contact_to | message  |
|====|==============|============|==========|
| 1  | 1            | 2          | some msg |
| 2  | 2            | 1          | reply    |
'----'--------------'------------'----------'

我创建一个新行,这样做:

public function add()
{
    $message = $this->Messages->newEntity();
    if ($this->request->is('post') && $this->request->is('ajax')) {
        $data = $this->request->getData();
        $data['contact_to'] = (int)$data['contact_to'];
        $data['contact_from'] = (int)$this->Auth->user('id');
        $message = $this->Messages->patchEntity($message, $data);
        if ($this->Messages->save($message)) {
            echo json_encode(['status' => 'success']);
            exit;
        }
        echo json_encode(['status' => 'error']);
        exit;
    }
}

这是我的 hasOne 关联:

$this->hasOne('ContactFrom', [
    'className' => 'Contacts',
    'foreignKey' => 'id',
    'bindingKey' => 'contact_from',
    'joinType' => 'INNER',
    'propertyName' => 'contact_from'
]);
$this->hasOne('ContactTo', [
    'className' => 'Contacts',
    'foreignKey' => 'id',
    'bindingKey' => 'contact_to',
    'joinType' => 'INNER',
    'propertyName' => 'contact_to'
]);

如您所见,我将一个 ID 传递到一个新行,但是它保存了除 ID 之外的所有内容。当我在 patchEntity 调用后 debug($message) 时,它像这样返回:

object(App\Model\Entity\Message) {
    'message' => 'asdfasdf',
    'date_sent' => object(Carbon\Carbon) {},
    '[new]' => true,
    '[accessible]' => [
        'contact_to' => true,
        'contact_from' => true,
        'message' => true,
    ],
    '[dirty]' => [
        'message' => true,
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Messages'
}

它删除了我的 ID。我假设这是因为我需要将实体传递给它,但是为了节省数据库调用,我怎样才能让它将 contact_tocontact_from id 保存到 table?

您选择的名称导致编组器发生冲突。

binding/foreign键和属性名称不能重名,这两个必须不同,因为前者是用来保存标识符的,而后者是用来保存标识符的保存一个实体或一个可以编组到一个实体中的数组——这两者都不适用于您传递的值,因此它将被丢弃。

您最好遵循 CakePHP 命名约定,并将 _id 附加到您的列中,即将它们命名为 contact_from_idcontact_to_id.

另见