在 Cakephp 中更改连接 contain() 条件

Change join contain() condition in Cakephp

我尝试使用 contain 来完全连接 2 个表,但我不知道如何更改条件:

$select= $this->Friends->find('all')
                ->order(['Friends.id' => 'ASC'])
                ->contain([
                    'Animals'
                ])
                ->where(['animal1_id'=> $animalsid,
                    'confirmed'=>'1'
                ]);
            $this->set(compact('select'));

所以看看 SQL:

 SELECT 
  * 
FROM 
  friends Friends 
  INNER JOIN animals Animals ON Animals.id = (Friends.animal2_id) 
WHERE 
  (
    animal1_id = 4 
    AND confirmed = 1
  ) 
ORDER BY 
  Friends.id ASC

问题是这个Friends.animal2_id我想换成Friends.animal1_id但是我不知道怎么办?也许还有其他方法?我尝试使用 join 但我只得到一个 table 而不是两个。

我考虑到你在两个模型 friendsbelongsTo 之间有关系=24=]动物.

所以你只需要更改关联中的外键名称,所以更新你的 Friends 模型中的关联

$this->belongsTo('Animals', [
    'foreignKey' => 'animal1_id',  //Here the column name you want to use for join
    'className'=>'Animals',
    'joinType' => 'INNER'
]);

编辑(评论查询):- 如果你想select其他表,你可以通过两种方式实现

在控制器中

$this->loadModel('OtherModelName');   //This will load your model to $this object
$other_table_result = $this->OtherModelName->find('all')->toArray();

使用原始 SQL 查询的方法,

$sql = "SELECT * FROM users"; 
$query = $this->connection->prepare($sql); 
$query->execute(); 
$result = $query->fetchAll();