[英]Could not view with composite pK CakePHP4
在cakephp-4.x 中,我無法訪問控制器對復合主鍵表的視圖操作。 (http://localhost:8765/invoice-items/view/1)
以下是cake bake
創建的代碼示例:
InvoiceItemsTable 類,其中主鍵被定義為復合。
class InvoiceItemsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('invoice_items');
$this->setDisplayField(['item_id', 'invoice_id', 'unit_id']);
$this->setPrimaryKey(['item_id', 'invoice_id', 'unit_id']);
$this->addBehavior('Timestamp');
$this->belongsTo('Items', [
'foreignKey' => 'item_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Invoices', [
'foreignKey' => 'invoice_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Units', [
'foreignKey' => 'unit_id',
'joinType' => 'INNER',
]);
}
...
InvoiceItemsController 視圖方法:
/**
* View method
*
* @param string|null $id Invoice Item id.
* @return \Cake\Http\Response|null|void Renders view
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$invoiceItem = $this->InvoiceItems->get($id, [
'contain' => ['Items', 'Invoices', 'Units'],
]);
$this->set(compact('invoiceItem'));
}
最后是來自 phpmyadmin 的invoice_items
表結構的屏幕截圖:
我試圖訪問像 (http://localhost:8765/invoice-items/view/1,1,6) 這樣的視圖,但我得到了同樣的錯誤... with primary key ['1,1,6'].
我不知道如何在 URL 中表示復合主鍵? 或者是什么問題?
我使用 CakePHP 4.4.2 版
Table::get()
期望復合鍵作為數組傳遞,例如[1, 1, 6]
。
假設您正在使用默認應用程序框架中的后備路由,您可以將其他參數作為路徑部分傳遞,例如:
/invoice-items/view/1/1/6
並在您的控制器操作中接受它們,例如:
public function view($itemId, $invoiceId, $unitId)
並從相應地構建一個數組以作為“id”傳遞給get()
:
$this->InvoiceItems->get([$itemId, $invoiceId, $unitId], /* ... */)
如果您使用具有固定參數的自定義路由,請以您喜歡的任何形式添加其他路由,例如使用破折號:
$routes
->connect(
'/invoice-items/view/{itemId}-{invoiceId}-{unitId}',
['controller' => 'InvoiceItems', 'action' => 'view']
)
->setPass(['itemId', 'invoiceId', 'unitId'])
->setPatterns([
'itemId' => '\d+',
'invoiceId' => '\d+',
'unitId' => '\d+',
]);
那么您的網址將如下所示:
/invoice-items/view/1-1-6
也可以看看
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.