每个Artikel
只有一个Barcode
。出于几个原因,我想拆分Artikel
模型和Barcode
模型。当我从artikel表中find()
某个东西时,它会返回一个包含正确条形码部分的数组。但是当我试图找到条形码时,数组的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'
)
);
物品表-id,名称,artikelgrupp_id和条形码表-id、artikel_id、条形码
将这些模型关联起来的正确方法是:文章有一个条形码,条形码属于文章
// 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
在条形码表中,所以Article hasOne Barcode可以正常工作。Barcode hasOne Article如果您的Article表中有barcode_id
,就会起作用。
但由于您需要条形码表中article_id
字段中的文章,因此应该使用belongsTo关系。
您是从哪个控制器进行这些呼叫的?如果您在同一个模型上,那么这是错误的,因为您必须通过模型之间的引用进行调用。例如,我假设您使用的是Artikel
模型,所以您的第一个调用是正确的,但第二个调用应该是$this->Artikel->Barcode->findById(1)