gpt4 book ai didi

mysql - 查找模仿 CakePhp 中的 LeftJoin

转载 作者:行者123 更新时间:2023-11-29 12:57:23 25 4
gpt4 key购买 nike

我有 3 个模型:

  1. 用户
  2. 喜欢
  3. 发帖

Like 在 user_idpost_id(这是其他 2 个模型的 id 列)上使用 CakePHP 约定设置了 2 个外键。

我想运行一个查找,在 Post 上使用外键条件模拟 sql 中的LEFT JOIN

我想要的详细信息:

  • 1:所有帖子。
  • 1a:如果该帖子得到了用户 XXX 的点赞,我希望将其包含在结果中
  • 1b:否则该帖子没有 ->Like 属性。

所以,如果我这样做:

$posts = $this->Post->find('all');

在 $posts 中,我拥有所有帖子,以及每个帖子的所有点赞。

读完这本书,我觉得我应该写一些这样的东西:

$options['joins'] = array(
array('table' => 'likes',
'alias' => 'Likes',
'type' => 'LEFT',
'conditions' => array(
'Post.id = Likes.post_id',
'Likes.user_id = 536f6a29-babc-4724-a74d-2ce100000000'
)
)
);


$posts = $this->Post->find('all', $options);

但这行不通。

希望这是清楚的。

最佳答案

那么你需要放入你的模型

class User extends AppModel
{
public $useTable = 'users';
public $primaryKey = 'id';
public $hasMany = array(
'Post',
'Like'
);
}

class Post extends AppModel
{
public $useTable = 'posts';
public $primaryKey = 'id';
public $belongsTo = array('User');
public $hasMany = array(
'Like'
);
}
class Like extends AppModel
{
public $useTable = 'likes';
public $primaryKey = 'id';
public $belongsTo = array('Post','User');
}

在你的 Controller 中

$this->loadModel("User");
$query = $this->User->find('all', array(
'joins' => array(
array(
'table' => 'posts',
'alias' => 'Post',
'type' => 'LEFT',
'conditions' => array(
'User.id = Post.user_id'
)
),
array(
'table' => 'likes',
'alias' => 'Like',
'type' => 'LEFT',
'conditions' => array(
'User.id = Like.user_id'
)
)
),
'conditions' => array(
'Post.id = Likes.post_id',
'Likes.user_id = 536f6a29-babc-4724-a74d-2ce100000000'
),
'order' => array(
'Post.id' => 'ASC'
),
'fields' => array('Post.*','User.id'),

'recursive' => -1
));

关于mysql - 查找模仿 CakePhp 中的 LeftJoin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23832185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com