cakephp 从父控制器创建新hasMany子控制器

sr4lhrrt  于 2022-11-11  发布在  PHP
关注(0)|答案(2)|浏览(151)

我有两个控制器“事件”和“活动”,两者都有许多“与会者”。

$this->hasMany('Attendees')
    ->setClassName('Attendees')
    ->setForeignKey('foreign_id')
    ->setConditions(array('Attendees.class' => 'Activity'))
    ->setDependent(true);

我正在使用Attendees表中的一个类和一个foreign_id来链接它们。例如,我想在ActivitiesController中创建addAttendee()函数来添加一个新的与会者,但我不确定如何继续。

public function addAttendee($id = null)
{
    $activity = $this->Activities->get($id, ['contain' => ['Venues', 'Contacts']]);

    if ($this->request->is('post'))
    {
        ??
    }

    $this->set(compact('activity'));
}

我找到了一些关于保存关联的文档,但没有关于创建新关联的文档。

uajslkp6

uajslkp61#

您可以创建一个新的Attendee实体,然后将其链接到您的$activity

$data = ['first_name' => 'blah', 'last_name' => ... fields]);
$attendee = $this->Attendee->newEntity($data);

$this->Attendee->link($activity, [$attendee]);

这是一个很好的例子,因为它是一个很好的例子。

8xiog9wr

8xiog9wr2#

我是这样做的。这是工作,但不确定这是否是正确的方式进行?

public function addAttendee($id)
{
    $activity = $this->Activities->get($id, ['contain' => ['Venues', 'Contacts']]);
    $attendee = $this->Activities->Attendees->newEmptyEntity();

    if ($this->request->is('post'))
    {
        $attendee = $this->Activities->Attendees->patchEntity($attendee, $this->request->getData() + ['class' => 'retreat', 'foreign_id' => $id]);

        if ($this->Activities->Attendees->save($attendee))
        {
            $this->Flash->success(__('The attendee has been saved.'));
            return $this->redirect(['action' => 'view', $id]);
        }

        $this->Flash->error(__('The attendee could not be saved. Please, try again.'));
    }

    $this->set(compact('activity', 'attendee'));
}

相关问题