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,因为它是错误的。