CakePHP hasOne 与 different table 的关系

CakePHP hasOne relationship with different table

每个 Artikel 正好有一个 Barcode。出于多种原因,我想拆分 Artikel 模型和 Barcode 模型。当我 find() 来自 artikel table 的东西时,它 returns 一个包含正确条形码部分的数组。但是当我尝试查找条形码时,数组的 artikel 部分为空。

这就是我的意思:

// $this->Artikel->findById(102);
array(
    'Artikel' => array(
        'id' => '102',
        'name' => 'Spätburgunder Spätlese Barrique',
        'erzeuger_id' => '679',
        'volumen_id' => '44',
        'artikelgruppe_id' => '17'
    ),
    'Barcode' => array(
        'id' => '1',
        'artikel_id' => '102',
        'barcode' => '123456'
    )
)

// $this->Barcode->findByBarcode(123456);
array(
    'Barcode' => array(
        'id' => '1',
        'artikelnummer' => 'DE51076',
        'barcode' => '123456'
    ),
    'Artikel' => array(
        'artikelnummer' => null, // this is null
        'name' => null, // this is null as well
        'erzeuger_id' => null, // also null
        'volumen_id' => null, // ……
        'artikelgruppe_id' => null // null
    )
)

知道我做错了什么吗?

这些是模型

// Barcode.php
public $hasOne = array(
    'Artikel' => array(
        'className' => 'Artikel',
        'foreignKey' => 'artikel_id'
    )
);


// Artikel.php
public $hasOne = array(
    'Barcode' => array(
        'className' => 'Barcode',
        'foreignKey' => 'artikel_id'
    )
);

您从哪个控制器发出这些呼叫?如果你在同一个模型上,那就错了,因为你必须通过模型之间的引用进行调用。例如,我假设你在 Artikel 模型中,所以你的第一个调用是正确的,但第二个应该是 $this->Artikel->Barcode->findById(1)

文章 table - id、名称、artikelgruppe_id 和条形码 table - id、artikel_id、条形码

关联这些模型的正确方法是:Article hasOne Barcode 和 Barcode belongsTo Article

// Artikel.php
public $hasOne = array(
    'Barcode' => array(
        'className' => 'Barcode',
        'foreignKey' => 'artikel_id'
    )
);

// Barcode.php
public $belongsTo = array(
    'Artikel' => array(
        'className' => 'Artikel',
        'foreignKey' => 'artikel_id'
    )
);

这里 article_id 在条码 table 中,因此文章 hasOne 条码按预期工作。如果您的文章 table.

中有一个 barcode_id,条形码 hasOne Article 就会起作用

但由于您需要条码 article_id 字段中的文章 table,您应该使用 belongsTo 关系。