关联 where 子句与数组 cakephp 3

association where clause with array cakephp 3

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

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

代码 table class

    <?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 寻求帮助

这是因为您正试图在匿名函数 (Closure) 调用中使用 $avoidedIDs,该函数在那里不可用。

您应该使其可用于该函数。

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

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

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