【发布时间】:2015-12-15 13:09:16
【问题描述】:
Cake PHP Version: 3.1.5
我在保存 hasOne 关联时遇到了问题,该关联在一张桌子上运行良好,但在另一张桌子上却不行。
Tickets和Cashdrafts在belongsTo关系中与Cashpositions相关。 Cashpositions 为他们的 id 持有两个 FK。因此,当自动创建新的现金头寸时,它会持有或者 ticket_id 或 cashdraft_id。第二个 FK 将为空。
问题是,Tickets-Cashpositions 保存工作正常,因此每次创建票证时都会创建相关的 cashpositions。但它不适用于 Cashdrafts-Cashpositions。我不明白为什么,因为设置和关系完全一样。
设置如下:
class CashpositionsTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Tickets', [
'foreignKey' => 'ticket_id'
]);
$this->belongsTo('Cashdrafts', [
'foreignKey' => 'cashdraft_id'
]);
}
}
class TicketsTable extends Table
{
public function initialize(array $config)
{
$this->hasOne('Cashpositions', [
'foreignKey' => 'ticket_id'
]);
}
}
class CashdraftsTable extends Table
{
public function initialize(array $config)
{
$this->hasOne('Cashpositions', [
'foreignKey' => 'cashdraft_id'
]);
}
}
然后在控制器中添加()函数:
class TicketsController extends AppController
{
public function add($memberId = null)
{
$ticket = $this->Tickets->newEntity();
if ($this->request->is('post')) {
$ticket = $this->Tickets->patchEntity($ticket, $this->request->data, [
// working fine: creates new cashposition for this ticket
'associated' => ['Cashpositions']
]);
if ($this->Tickets->save($ticket)) {
$this->Flash->success(__('ticket saved'));
return $this->redirect(['action' => 'view', $ticket->$id]);
} else {
$this->Flash->error(__('ticket could not be saved'));
}
}
class CashdraftsController extends AppController
{
public function add()
{
$cashdraft = $this->Cashdrafts->newEntity();
if ($this->request->is('post')) {
$cashdraft = $this->Cashdrafts->patchEntity($cashdraft, $this->request->data,[
// fail: no associated record created
'associated' => ['Cashpositions']
]);
if ($this->Cashdrafts->save($cashdraft)) {
$this->Flash->success(__('cashdraft saved.'));
return $this->redirect(['action' => 'view', $cashdraft->id]);
} else {
$this->Flash->error(__('cashdraft could not be saved'));
}
}
}
我调试了 $ticket 和 $cashdraft。但我不能说我理解输出,因为:
票的数组将显示所有相关数据,但不显示现金头寸,尽管它的新记录已成功创建...
并且未创建相关现金头寸的新现金汇票的数组将如下所示并为其显示“null”:
object(App\Model\Entity\Cashdraft) {
'id' => (int) 10,
'amount' => (float) -7,
'created' => object(Cake\I18n\Time) {
'time' => '2015-12-13T20:03:54+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-12-13T20:03:54+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'cashposition' => null, // this part not even showing up for a "ticket" in the debug
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'Cashdrafts'
}
在 DebugKit 的 SQL 中,我可以看到对于票证,已将 INSERT 插入到相关的现金头寸表中。但是对于现金汇票,相关表中没有插入。所以很明显,Cake 甚至没有尝试创建关联的记录。
我现在真的没有主意了!在数据库本身中,两个 FK 的设置完全相同,名称正确等。
有人知道问题可能是什么,或者我可以在哪里进一步搜索导致第二个关联不起作用的原因?谢谢!
【问题讨论】:
-
您使用的是您所说的
Cake PHP Version: 1.3.5,还是您标记的cakephp-3.0? -
哦,抱歉,我没看到我在那儿换了号码,我会改正的。我使用的是 3.1.5 版。
标签: php mysql cakephp-3.1