CakePHP 3.6.11: предложение Where соединяемых таблиц

У меня есть эти 3 таблицы:

клиенты:

customerstable

Сервисы:

servicestable

обслуживание клиентов:

customerservicestable

С этим отношением в CustomerservicesTable.php:

$this->belongsTo('Customers')
->setForeignKey('customerid');

$this->belongsTo('Services')
->setForeignKey('serviceid');

В Customers страница редактирования я хочу добавить таблицу с Services конкретного клиента (а затем добавить новый, редактировать существующий и т. д.).

Так в Template\Customers\edit.ctp У меня есть эта таблица:

<h3><?= __('Services') ?></h3>
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th scope="col"><?= $this->Paginator->sort('Date') ?></th>
<th scope="col"><?= $this->Paginator->sort('Service') ?></th>
<th scope="col"><?= $this->Paginator->sort('Price') ?></th>
<th scope="col" class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($services as $service): ?>
<tr>
<td><?= h($service->created) ?></td>
<td><?= h($service->title) ?></td>
<td><?= $this->Number->format($service->price) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $customer->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $customer->id]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $customer->id], ['confirm' => __('Are you sure you want to delete # {0}?', $customer->id)]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

и в edit функция Controller\CustomersController.php Я добавил эти строки:

//Get customerservices for specific customer
$servicesTable = TableRegistry::get('Services');
$services = $servicesTable->find('all');//->where(['Services.Customerservices.id =' => $this->data['Customers']['id']]);

$this->set(compact('services'));

И я прокомментировал where часть. Как я могу изменить его, чтобы получать только те услуги, которые принадлежат конкретному клиенту? с использованием customerservicesTable?

И после этого я могу редактировать непосредственно CustomerservicesController.php реализовать добавить, редактировать функции этой таблицы?

РЕДАКТИРОВАТЬ

После предложения ndm я изменил это так:

//Get customerservices for specific customer
$servicesTable = TableRegistry::get('Services');
$services = $servicesTable->find()->matching('Customerservices', function(\Cake\ORM\Query $q) {
return $q->where(['Customerservices.customerid' => $this->data['Customers']['id']]);
});

Но это не работает. Вероятно, $this->data['Customers']['id'] не работает, потому что, если я заменю его на 1 (идентификатор клиента), он будет работать как положено. Есть идеи, почему не работает?

0

Решение

Попробуйте это вместо этого:

$servicesTable = TableRegistry::get('Services');

$customerId = $this->data['Customers']['id'];
// how about $this->request->getData('Customer.id') ?

// pass variable to function with `use`
$services = $servicesTable->find()->matching('Customerservices', function(\Cake\ORM\Query $q) use ($customerId) {
return $q->where(['Customerservices.customerid' => $customerId]);
});

Если вы не уверены, что $this->data['Customers']['id'] содержит то, что вы ожидаете, просто посмотрите, что там:

debug($this->data['Customers']);

// or
debug($this->data);

// or
print_r($this->data['Customers']);

Если это данные, опубликованные объектом запроса, посмотрите здесь: https://book.cakephp.org/3.0/en/controllers/request-response.html#request-body-data

// An input with a name attribute equal to 'MyModel[title]' is accessible at
$title = $this->request->getData('MyModel.title');
0

Другие решения

Я исправил это, добавив use ($id) а также $id вместо $this->data['Customers']['id'] :

//Get customerservices for specific customer
$servicesTable = TableRegistry::get('Services');
$services = $servicesTable->find()->matching('Customerservices', function(\Cake\ORM\Query $q) use ($id) {
return $q->where(['Customerservices.customerid' => $id]);
});
0