【问题标题】:Saving data using where clause使用 where 子句保存数据
【发布时间】:2017-03-31 15:28:16
【问题描述】:

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

还有更简单的吗?

【问题讨论】:

    标签: cakephp orm save associations cakephp-3.0


    【解决方案1】:

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

    我个人会使用查找器来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();
    

    另见

    【讨论】:

    • 感谢您的洞察!
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 2016-04-05
    • 2019-10-04
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    相关资源
    最近更新 更多