【问题标题】:association where clause with array cakephp 3与数组 cakephp 3 关联的 where 子句
【发布时间】:2016-05-14 09:05:01
【问题描述】:

基本上我想做的是用 cakephp 3 查询生成器编写这个查询:

SELECT * FROM question as q innerjoin answers as a where q.question = $question AND a.id NOT IN = $avoidedIDs

表类代码

    <?php
namespace App\Model\Table;


use Cake\ORM\Table;
use App\Model\Entity\Comlib;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Validator;
use Cake\ORM\TableRegistry;

class ComlibsTable extends Table {

public function initialize(array $config) {
    parent::initialize($config);
 $this->table('questions');
// join the tables 
$this->hasMany('Answers' , [
'foreignKey' => 'question_id'
]);



    }

public function LFA( $live_req) {
$query = $this->find()->where(['question' => $live_req])->contain(['Answers'])->LIMIT(6);
$query = $query->toArray();

//include 5 answer
return $query;

    }
    public function LFM($theid , $avoidedIDs, $question )
    {
    $query = $this->find()->where(['question' => $question])->contain(['Answers' => function($q){
    return $q
    ->where(['Answers.id NOT IN' => $avoidedIDs] );
    }
    ]);
    $query = $query->toArray();
    debug($query);
    return $query;

    }
}

我得到的错误是:无法使用字段 (Answers.id) 的空值列表生成条件。 但是当我 print_r($avoidedIDs) 我得到了我传递的值,所以我确定 $avoidedIDs 不是空的,至少没有超出包含函数,这对我来说更复杂,但是当我输入一个数字而不是我的变量它将执行,如果我输入 1,2,3,4 它仍然只会执行第一个! 这两天我做错了什么?????? tnx 寻求帮助

【问题讨论】:

    标签: filtering cakephp-3.0 where-clause query-builder


    【解决方案1】:

    这是因为您试图在匿名函数(闭包)调用中使用 $avoidedIDs,而该函数在此处不可用。

    您应该使其可用于该功能。

    ->contain(['Answers' => function($q) use ($avoidedIDs){..}
    

    闭包也可以从父作用域继承变量。任何此类 变量必须传递给使用语言构造。

    http://www.php.net/manual/en/functions.anonymous.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 2020-08-08
      • 2015-08-31
      • 1970-01-01
      • 2020-03-17
      • 2014-11-07
      • 1970-01-01
      相关资源
      最近更新 更多