使用where子句保存数据

时间:2017-03-31 15:28:16

标签: cakephp orm save associations cakephp-3.0

我希望能够在提供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.'));
    }
}

更简单吗?

1 个答案:

答案 0 :(得分:1)

没有这样的保存语法,事先检索正确的实体是正确的方法,并且实际上并没有更简单的"方式 - 但肯定有优化的空间。

就个人而言,我会使用查找程序来DRY进行操作,即在Medium.first.details上创建一个限制特定联盟用户的查找器:

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()所做的。

你可以通过为游戏ID使用动态查找器来进一步减少事情:

Table::get()

另见