dousi0144 2018-07-22 18:57
浏览 209
已采纳

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

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):

enter image description here

Any help is greatly appreciated!

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

  • 写回答

1条回答 默认 最新

  • dongqiu5184 2018-07-22 19:03
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?