简体   繁体   English

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

[英]MySQL JOIN - json returns data only from one table

I have a small problem with JSON returning only data from one table when put through ajax on frontend without userName that's coming from Users table. 我有一个小问题,当将JSON通过前端的ajax放入而没有来自Users表的userName时,JSON仅从一个表返回数据。 Backend looks fine when checked with var_dump: 使用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 query (executes properly alone and returns desired result - username is included in the result): MySQL查询(单独正确执行并返回所需结果-用户名包含在结果中):

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

method in class Privatemessage that uses the query: 使用查询的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: 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); console.log(response.success); in ajax returns the below in Chrome dev console (again, userName is missing): 在ajax中,在Chrome开发者控制台中返回以下内容(再次,缺少userName ):

在此处输入图片说明

Any help is greatly appreciated! 任何帮助是极大的赞赏!

EDIT: I've implemented JsonSerializable in Privatemessage class and forgot to return userName in jsonSerialize() method within the class. 编辑:我已经在Privatemessage类中实现了JsonSerializable,却忘记了在类内的jsonSerialize()方法中返回userName。

Your class Privatemessage may need to have a public $username property in order for this to work. 您的班级Privatemessage可能需要具有公共的$ username属性,此功能才能起作用。 It depends on how you've implemented the JSON conversion. 这取决于您如何实现JSON转换。 From the comment, it seems like you're using JsonSerializable, so you'd need to make sure all present fields are accounted for in the jsonSerialize method. 从注释中看,您似乎正在使用JsonSerializable,因此您需要确保在jsonSerialize方法中考虑了所有当前字段。


Looking at your code, if the goal is just to generate a JSON response, I don't see the point of creating an instance of Privatemessage here. 查看您的代码,如果目标只是生成JSON响应,则在此处看不到创建Privatemessage实例的意义。 Why don't you just use the existing objects returned from PDO? 您为什么不只使用从PDO返回的现有对象?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM