【问题标题】:CakePHP hasOne relationship with different tableCakePHP 与不同的表有一个关系
【发布时间】:2015-02-06 12:23:58
【问题描述】:

每个Artikel 恰好有一个Barcode。出于几个原因,我想拆分 Artikel 模型和 Barcode 模型。当我 find() artikel 表中的某些内容时,它会返回一个包含正确条形码部分的数组。但是当我尝试查找条形码时,数组的 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'
    )
);

【问题讨论】:

  • 我认为你必须写一个从 Barcode 到 Artickel 的 belongsTo 关系

标签: php cakephp relationship


【解决方案1】:

文章表 - id、名称、artikelgruppe_id 和条形码表 - 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 在条形码表中,所以文章有一个条形码按预期工作。如果您的文章表中有 barcode_id,条码 hasOne Article 会起作用。

但由于需要Barcode表中article_id字段中的文章,所以应该使用belongsTo关系。

【讨论】:

  • 太棒了,伙计!做到了:)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-06
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多