使用where子句保存数据

问题描述:

我希望能够在提供where子句的同时保存数据。使用where子句保存数据

我有以下代码:

$game = $this->Games->newEntity(); 
if ($this->request->is('post')) { 
    $game = $this->Games->patchEntity($game, $this->request->data); 
    if ($this->Games->save($game)) { 
     $this->Flash->success(__('The game has been saved.')); 

     return $this->redirect(['action' => 'index']); 
    } else { 
     $this->Flash->error(__('The game could not be saved. Please, try again.')); 
    } 
} 

我想这一点,但没有奏效:

$this->Games->save($game)->innerJoinWith('Leagues', function ($q) use($s) { 
        return $q->where(['Leagues.user_id' => $s]); 
       } 
      ) 

我怀疑有人做了一个寻找where子句和补丁请求数据呢?

$game = $this->Games->find()->innerJoinWith('Leagues', function ($q) { 
    return $q->where(['Leagues.user_id' => $this->Auth->user('id')]); 
}) 
->where(['Games.id' => $id]) 
->first(); 

if(! count($game)){ 
    $this->Flash->error(__('The game could not be found.')); 
    return $this->redirect(['action' => 'index']); 
} 

if ($this->request->is('post')) { 
    $game = $this->Games->patchEntity($game, $this->request->data); 
    if ($this->Games->save($game)) { 
     $this->Flash->success(__('The game has been saved.')); 

     return $this->redirect(['action' => 'index']); 
    } else { 
     $this->Flash->error(__('The game could not be saved. Please, try again.')); 
    } 
} 

更简单吗?

没有这种保存语法,事先检索合适的实体是正确的方法,并没有真正的“更简单”方式 - 但是确实有优化的空间。

个人而言,我会用发现者来DRY东西,即创建制约事情联赛特定用户GamesTable取景器:

public function findForLeagueUser(\Cake\ORM\Query $query, array $options) 
{ 
    if (!isset($options['id'])) { 
     throw new \InvalidArgumentException('The `id` option is invalid or missing.'); 
    } 

    return $query 
     ->innerJoinWith('Leagues', function (\Cake\ORM\Query $query) use ($options) { 
      return $query->where([ 
       $this->Leagues->aliasField('user_id') => $options['id'] 
      ]); 
     }); 
} 

,并结合东西,在控制器动作:

$game = $this->Games 
    ->find('forLeagueUser', ['id' => $this->Auth->user('id')]) 
    ->where(['Games.id' => $id]) 
    ->first(); 

您也可以使用firstOrFail()代替,如果找不到记录则会引发异常,这也是Table::get()在内部所做的。

而且你可以通过使用动态取景器的游戏ID进一步降低的事情:

$game = $this->Games 
    ->findById($id) 
    ->find('forLeagueUser', ['id' => $this->Auth->user('id')]) 
    ->first(); 

又见

+0

感谢您的见解! – TekiusFanatikus