gpt4 book ai didi

php - 使用 cakephp 从数据库查找表连接值

转载 作者:行者123 更新时间:2023-11-29 14:20:39 25 4
gpt4 key购买 nike

我正在尝试在 cakephp 的 View 中访问用户名。我获得了一个用户 ID,我需要使用它来查找存储在不同表中的用户名。

我正在检索显示的表格是消息,如下所示

id |  title | message | from_user  | to_user | date

包含用户名的用户表

id | username | email | password

无论如何,我怎样才能在消息中查找 from_user 的用户名?我仍然习惯于蛋糕,所以我不知道如何在不实际编写查询的情况下制作“连接”语句。

我应该从 Controller 中的操作发送用户名还是可以从 View 中发送用户名?

编辑-我让它工作了

现在这是我的索引函数

public function index() {

$options['joins'] = array(
array('table' => 'Users',
'type' => 'inner',
'fields' => array('user.username'),
'conditions' => array(
'Message.from_user = User.id',
'alias' => 'user_id')
)
);

$message = $this->Message->find('all', $options);

$this->set('messages', $message);
}

我将其添加到我的消息 Controller 中,现在显示用户名,但仅适用于第一条消息。其他的都是空白。

public $belongsTo = array('User');

最佳答案

您必须重新定义消息模型中的关系:

public $belongsTo = array(
'Sender' => array(
'className' => 'User',
'foreignKey' => 'from_user'
),
'Recipient' => array(
'className' => 'User',
'foreignKey' => 'to_user'
)
);

关于php - 使用 cakephp 从数据库查找表连接值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11813176/

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