gpt4 book ai didi

php - MySQL JOIN - json 仅从一张表返回数据

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

我有一个小问题,当在前端通过 ajax 进行处理时,JSON 仅返回一个表中的数据,而没有来自 Users 表的 userName 。使用 var_dump 检查时后端看起来很好:

/home/maciek/Workspace/Communic/public/admin/privMessage.php:11:
array (size=3)
0 =>
object(Privatemessage)[6]
private 'id' => string '4' (length=1)
private 'senderId' => string '2' (length=1)
private 'receiverId' => string '1' (length=1)
private 'creationDate' => string '2017-06-28 23:49:15' (length=19)
private 'text' => string 'asdasdasda' (length=10)
private 'readStatus' => string '1' (length=1)
**private 'userName' => string 'stefan' (length=6)**

MySQL 查询(单独正确执行并返回所需结果 - 用户名包含在结果中):

SELECT p.*, u.username FROM PrivateMessage p RIGHT JOIN Users u ON p.sender_id=u.id WHERE receiver_id=:receiver_id

Privatemessage类中使用查询的方法:

    static public function loadAllRcvdPrvMsgsByUserId(PDO $pdo, $receiverId) {
$stmt = $pdo->prepare("SELECT p.*, u.username FROM PrivateMessage p RIGHT JOIN Users u ON p.sender_id=u.id WHERE receiver_id=:receiver_id");
$result = $stmt->execute([
'receiver_id' => $receiverId
]);

$rcvdPrvMsgsArray = [];

if ($result === true && $stmt->rowCount() > 0) {
while ($row = $stmt->fetchAll(PDO::FETCH_OBJ)) {

foreach ($row as $dbPrvMessage) {
$loadedPrvMsg = new Privatemessage($pdo);
$loadedPrvMsg->id = $dbPrvMessage->id;
$loadedPrvMsg->senderId = $dbPrvMessage->sender_id;
$loadedPrvMsg->receiverId = $dbPrvMessage->receiver_id;
$loadedPrvMsg->creationDate = $dbPrvMessage->privatemessage_datetime;
$loadedPrvMsg->text = $dbPrvMessage->privatemessage_text;
$loadedPrvMsg->readStatus = $dbPrvMessage->privatemessage_readstatus;
$loadedPrvMsg->userName = $dbPrvMessage->username;

$rcvdPrvMsgsArray[] = $loadedPrvMsg;
}
}
return $rcvdPrvMsgsArray;
}
return null;
}

js ajax:

    function getReceivedPrivateMsg() {
$
.ajax({
url: '../../../rest/rest.php/privateMessage',
type: 'GET'
})
.done(function (response) {

console.log(response.success);

})
.fail(function (error) {
console.log('Create sent private message error', error);
});
}

console.log(响应.成功); ajax 在 Chrome 开发控制台中返回以下内容(同样,缺少 userName):

enter image description here

非常感谢任何帮助!

EDIT: I've implemented JsonSerializable in Privatemessage class and forgot to return userName in jsonSerialize() method within the class.

最佳答案

您的 Privatemessage 类可能需要有一个公共(public) $username 属性才能使其正常工作。这取决于您如何实现 JSON 转换。从评论来看,您似乎正在使用 JsonSerialized,因此您需要确保 jsonSerialize 方法中考虑了所有存在的字段。

<小时/>

看看你的代码,如果目标只是生成 JSON 响应,我不认为在这里创建 Privatemessage 实例有什么意义。为什么不直接使用从 PDO 返回的现有对象?

return $stmt->fetchAll(PDO::FETCH_OBJ);

关于php - MySQL JOIN - json 仅从一张表返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51468335/

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