CakePHP关联:句柄空id

CakePHP关联:句柄空id,php,sql,cakephp,associations,Php,Sql,Cakephp,Associations,我有这个模型: Proforma ->hasMany('ItemProformas', ['foreignKey' => 'proforma_id']); ->belongsTo('Customers', ['foreignKey' => 'customer_id']); ->belongsTo('ProformaStates', ['foreignKey' => 'proforma_state_id']); ->hasMany('Inv

我有这个模型:

Proforma
  ->hasMany('ItemProformas', ['foreignKey' => 'proforma_id']);
  ->belongsTo('Customers', ['foreignKey' => 'customer_id']);
  ->belongsTo('ProformaStates', ['foreignKey' => 'proforma_state_id']);
  ->hasMany('Invoices', ['foreignKey' => 'proforma_id']);

ItemProformas
  ->belongsTo('Proformas', ['foreignKey' => 'proforma_id', 'joinType' => 'INNER']);
  ->belongsTo('ItemDeliveryNotes', ['foreignKey' => 'item_delivery_note_id']);

ItemDeliveryNotes
    ->belongsTo('DeliveryNotes', ['foreignKey' => 'delivery_note_id', 'joinType' => 'INNER']);
    ->belongsTo('ItemOrders', ['foreignKey' => 'item_order_id']);
    ->belongsTo('ItemOrdersTypes', ['foreignKey' => 'item_orders_type_id']);
    ->belongsTo('Products', ['foreignKey' => 'product_id']);
每个
ItemProforma
可以有一个
ItemDeliveryNotes
,否则外键将为
null
。这里是我的
paginate
呼叫:

$this->paginate = [
    'contain' => [
        'Customers',
        'ProformaStates',
        'ItemProformas' => ['ItemDeliveryNotes' => ['DeliveryNotes']]
    ]
];
通过这个模型,我得到了所有设置了
item\u delivery\u note\u id
itemProforma
。相反,我很想把它们都买下来,即使
item\u delivery\u note\u id
null

我不确定
belongsTo
在这里是否正确(我指的是
项目形式定义中)。但是
hasOne
意味着它有一个关联行,而不是可能有一个


检索所有
itemproforms
的正确语法是什么,即使它们没有任何关联的
ItemDeliveryNote
?但是如果有,我还需要检索
ItemDeliveryNote
对象。

关联类型取决于您的模式。如果外键在源表中,则它是
belongsTo
,如果外键在目标表中,则它是
hasOne

相关记录是否必须存在主要取决于模式,而不是关联的类型。如果外键可为空,则相关记录是可选的。如果以及如何在应用程序级别实施该约束则是另一回事

也就是说,
ItemDeliveryNotes
DeliveryNotes
都属于默认情况下使用联接的
belongsTo
,因此这两个关联都将联接到同一查询中,并且由于您已将
DeliveryNotes
关联配置为使用
内部联接,它将排除不存在
DeliveryNotes
的行,当然,当不存在
ItemDeliveryNotes
时也是如此

假设您的模式建模正确/正确,例如,您可以更改您的关联配置,以在适用的情况下默认使用
LEFT
连接,或者您可以在每个查询的基础上更改包含的配置(手动或使用自定义查找器):

$this->paginate=[
“包含”=>[
"顾客",,
“形式”,
“项目形式”=>[
'ItemDeliveryNotes'=>[
“DeliveryNotes'=>[
“joinType”=>\Cake\Database\Query::JOIN\u TYPE\u LEFT,
],
],
],
],
];
更改
ItemDeliveryNotes
的获取策略也可能会起作用(尽管根据记录的数量可能会有很大的负担),即使用
select
策略而不是
join
策略,然后在单独的查询中检索关联的
ItemDeliveryNotes
记录,因此不会影响
项目形式的检索:

$this->paginate=[
“包含”=>[
"顾客",,
“形式”,
“项目形式”=>[
'ItemDeliveryNotes'=>[
“策略”=>\Cake\ORM\Association::strategy\u SELECT,
“交货通知单”,
],
],
],
];

谢谢,我在模型中将连接类型更改为LEFT,因为它是错误的。