简体   繁体   中英

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. Backend looks fine when checked with 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):

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:

    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); in ajax returns the below in Chrome dev console (again, userName is missing):

在此处输入图片说明

Any help is greatly appreciated!

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

Your class Privatemessage may need to have a public $username property in order for this to work. It depends on how you've implemented the JSON conversion. 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.


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. Why don't you just use the existing objects returned from PDO?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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