【问题标题】:Change join contain() condition in Cakephp在 Cakephp 中更改 join contains() 条件
【发布时间】:2018-07-21 10:29:31
【问题描述】:

我尝试使用 contains 对 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.animal1_id 更改这个 Friends.animal2_id 但我不知道怎么做?也许还有其他方法?我尝试使用 join,但我只得到一个表而不是两个。

【问题讨论】:

  • "animal1_id" & "confirmed" 列属于哪个表、朋友或动物?
  • @bikash.bilz 到那里的表朋友我有 'animal1_id' 和 'animal2_id' 并确认。当我使用包含时,他会自动将“animal2_id”加入,但我需要“animal1_id”

标签: cakephp join cakephp-2.0 cakephp-3.0 contain


【解决方案1】:

我认为你在两个模特朋友动物之间有belongsTo关系。

所以您只需要更改关联中的 foreignKey 名称,因此更新您的 Friends 模型中的关联

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

编辑(用于评论查询):- 如果要选择其他表,可以通过两种方式实现

在控制器中

$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();

【讨论】:

  • 我找到了另一种方法,也可以使用关节,感谢您的帮助。
  • 你知道如何从表中选择*...如果我使用加入 cakephp,如果我要制作 $this->Tablename->find('全部')...?
  • @Christian Yes 是解决您的问题的替代方法,可以在查找中使用加入。
  • @Christian 我不确定你想要实现什么,仍然使用 ORM 可以节省你的时间,所以最好使用 ORM 而不是使用原始查询。我正在添加一些代码来帮助你
猜你喜欢
  • 2012-11-03
  • 1970-01-01
  • 2011-07-10
  • 2015-01-17
  • 1970-01-01
  • 2020-01-28
  • 2016-07-16
  • 2015-04-10
  • 2012-05-20
相关资源
最近更新 更多