Cake PHP添加和编辑记录

时间:2017-05-24 10:03:04

标签: php cakephp orm associations cakephp-3.x

所以我不熟悉PHP。我正在尝试将我的数据库结构化,以便用户可以向场地添加活动,但如果场地已经具有该特定活动,则不会添加记录。例如;

玫瑰和皇冠= Pin-Pong
玫瑰和皇冠=斯诺克台球 玫瑰和皇冠=乒乓球

目前,即使活动相同,您也可以多次拥有相同的场地。例如;

玫瑰和皇冠= Pin-Pong
玫瑰和皇冠=斯诺克台球 玫瑰和皇冠=乒乓球
玫瑰和皇冠= Pin-Pong

public function add()
{
    $venueActivity = $this->VenueActivities->newEntity();
    if ($this->request->is('post')) {
        $venueActivity = $this->VenueActivities->patchEntity($venueActivity, $this->request->data);
        if ($this->VenueActivities->save($venueActivity)) {
            $this->Flash->success(__('The venue activity has been saved.'));

            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The venue activity could not be saved. Please, try again.'));
        }
    }
    $venues = $this->VenueActivities->Venues->find('list', ['limit' => 200]);
    $activities = $this->VenueActivities->Activities->find('list', ['limit' => 200]);
    $this->set(compact('venues', 'venueActivity', 'activities'));
    $this->set('_serialize', ['venueActivities']);
}

我已经能够弄清楚如何完全覆盖记录,因此它们只是场地的一条记录(见下面的代码),但是如果输入相同的活动,我只需要覆盖记录。但是你可以拥有所有不同的活动。

public function add()
{

    $venueActivity = $this->VenueActivities->newEntity();
    if($this->request->is('post')) {

        $venueActivity = $this->VenueActivities->patchEntity($venueActivity, $this->request->data);

        $oldVenueActivity = $this->VenueActivities->find()->where(['venue_id' => $venueActivity->venue_id]);

        foreach($oldVenueActivity as $activity) {
            $this->VenueActivities->delete($activity);
        } 

        if ($this->VenueActivities->save($venueActivity)) {
            $this->Flash->success(__('The venue activity has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The venue activity could not be saved. Please, try again.'));
        }
    }

    $venues = $this->VenueActivities->Venues->find('list', ['limit' => 200]);
    $activities = $this->VenueActivities->Activities->find('list', ['limit' => 200]);
    $this->set(compact('venues', 'venueActivity', 'activities'));
    $this->set('_serialize', ['venueActivities']);
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

请考虑重新考虑针对此特定问题的方法。

您现在拥有的:场地,活动和场地活动。您正在使用VenueActivities,一起加入场地和活动。

你应该做什么(在我看来):只烘焙场地和活动,并在他们的桌面类中为他们设置belongsToMany关联。然后,在VenueController中,您可以创建manageActivities函数:

public function manageActivities($id = null){
    $venue = $this->Venues->get($id);
    if($this->request->is(['post','put'])){
        //patch entity and save
    }
    $activities = $this->Venues->Activities->find('list');
    $this->set(compact('venue','activities');
}

然后,在manage_activities.ctp中:

$this->Form->input('activities._ids', ['multiple' => 'checkbox']);

上面的代码将生成多个可选择的活动列表。如果您要检查其他活动,将添加与其关联。如果您取消选中现有的关联,则将删除与此特定活动的关联,并保留其余选定活动。

其他信息:https://book.cakephp.org/3.0/en/orm/associations.html#belongstomany-associations