【问题标题】:Check if record exists in database using BuildRules (CakePHP 3)使用 BuildRules (CakePHP 3) 检查数据库中是否存在记录
【发布时间】:2017-02-12 21:57:54
【问题描述】:

我想检查用户使用 HTTP 请求传递的 ID 是否存在于 cakephp 的另一个表中。现在,我尝试使用:

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn('id_venue', 'venues'));
    return $rules;
}

但它似乎不起作用。这条规则在一个预订表中,在这个表中我有一个名为 id_venue 的列,我有另一个名为 Venues 的表,它也有一个名为 id_venue 的主键。

public function initialize(array $config)
{
    parent::initialize($config);
    $this->table('reservations');
    $this->primaryKey('id_reservation');
    $this->hasOne('Venues');
}

我已将我的 Reservations 表与我的 Venues 表相关联

感谢您的帮助。

【问题讨论】:

    标签: sql database api cakephp cakephp-3.0


    【解决方案1】:

    没有完全理解您需要的调用类型,但如果您只需要检查特定行是否已存在于数据库中,您可以使用 exists

    $table = TableRegistry::get('Venues');
    $conditions = ['id' => 15];
    $exists = $table->exists($conditions); //returns true or false
    

    这类问题已经得到解答: Check if record exists in CakePHP3

    【讨论】:

    • 很好,但我必须检查用户在 HTTP 请求中使用 curl 传递的 id,例如,在您的代码中,id 是硬编码的。
    【解决方案2】:

    existsIn 的第一个参数是一个数组,我相信第二个参数是区分大小写的。试试

    $rules->add($rules->existsIn(['id_venue'], 'Venues'));
    

    【讨论】:

      猜你喜欢
      • 2012-08-13
      • 1970-01-01
      • 2013-08-07
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      相关资源
      最近更新 更多