【问题标题】:CakePHP 3.2 find first with whereCakePHP 3.2 先用 where 找到
【发布时间】:2016-12-11 15:36:46
【问题描述】:

我正在使用 CakePHP 3.2。这是我的查找查询:

  $a=$this->A->find('all', ['where' => [ 'b=='=>5, 'c>'=>1000 ]])->first();   

  // For debuging what I receive:
  $data=$a->toArray();
  print_r($data);

我想选择'A'中的第一条记录,其'b'列等于5,'c'列大于1000。我做错了什么?上述查询返回 'A' 表中的所有记录。

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    简单

    $a = $this->A->find()
        ->where([ 'b' => 5, 'c >' => 1000 ])
        ->first();   
    
    debug($a)
    

    你不需要调用 toArray() 因为 first 已经返回了一个实体

    【讨论】:

    • toArray 仅用于调试需要。您的代码不起作用:在布尔值上调用成员函数 find()
    • 当然,您可以将实体转换为数组,但出于调试目的,它提供或多或少相同的信息,因此我认为它不是很有用。代码也是正确的(只要您实际上有一个名为 A 的模型)。
    【解决方案2】:

    应该是这样的: $data = $this->A->find()->where(['b' => 5, 'c >' => 1000])->first();

    【讨论】:

      【解决方案3】:

      使用conditions 而不是where

      $a=$this->A->find('all', ['conditions' => ['b'=>5, 'c >'=>1000]])->first();
      

      【讨论】:

      • 确实有效。您能否解释一下为什么我的“在哪里”不起作用。我以前从未使用过“条件”。有什么区别?
      • 因为这是官方语法。请参阅book.cakephp.org/3.0/en/orm/…中的“find() 支持的选项列表”
      • 谢谢!我从 cake 1.3 迁移到 3.2,它已经改变了
      • find all cars with name prefix 'A' but take only the first one vs find first car with name prefix 'A'...looool
      【解决方案4】:

      使用条件而不是位置

      $query = $articles->find('all', [
          'conditions' => ['Articles.title LIKE' => '%Ovens%']
      ]);
      $result = $query->toArray();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-13
        • 1970-01-01
        相关资源
        最近更新 更多