MySQL JOIN-JSON仅从一个表返回数据

时间:2018-07-22 18:57:20

标签: php mysql json

我有一个小问题,当JSON通过前端的ajax放入而没有 Users 表时,它仅从一个表返回数据。使用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(response.success);在ajax中,在Chrome开发者控制台中返回以下内容(同样,缺少 userName ):

enter image description here

非常感谢您的帮助!

  

编辑:我已经在Privatemessage类中实现了JsonSerializable,却忘记了在类内的jsonSerialize()方法中返回userName。

1 个答案:

答案 0 :(得分:0)

您的班级Privatemessage可能需要具有一个公共的$ username属性,此属性才能起作用。这取决于您如何实现JSON转换。从注释中看,您似乎正在使用JsonSerializable,因此您需要确保在jsonSerialize方法中考虑了所有当前字段。


查看您的代码,如果目标只是生成JSON响应,则在此处看不到创建Privatemessage实例的意义。为什么不只使用从PDO返回的现有对象?

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