Why does belongsTo () return null?

I have two models and two tables. Name of the first model Inboxwith the database structure:

enter image description here

And the middle name of the model StudentDatawith the database structure:

enter image description here

And I will return using route('/sended')all the messages, using my method to get the necessary messages:

public function getMessages($message_type = "new")
{
    $user_id = Auth::user()->id;

    $inbox = new Inbox();

    $paginate = 3;

    switch ($message_type) {

        case 'sended':
            $messages = $inbox->where('sender', $user_id)
                              ->where('trashed_in_sender', 0)
                              ->where('show_in_sender', 0)
                              ->orderBy('created_at', 'desc')
                              ->paginate($paginate);
            break;
        default:
            return abort(404);
            break;
    }

    return $messages;
}

And I have methods in my model Inbox:

public function messageSender()
{
    return $this->belongsTo("App\StudentData", 'sender');
}

public function messageRecipient()
{
    return $this->belongsTo("App\StudentData", 'recipient');
}

When I call into view $message->messageSenderas a result set to NULL. Why can't I get data using table sender idfrom inboxesin tablestudent_datas

+4
source share
1 answer

So, I have a few questions ....

1) User StudentData? 2 - 1:1? User?
( ?)

2) , ... User, . .

, "", "" "", .
"" :

public function messageSender()
{
    return $this->belongsTo("App\User", 'sender');
}

public function messageRecipient()
{
    return $this->belongsTo("App\User", 'recipient');
}

? User,

public function sentMessages()
{
    return $this->hasMany("App\Inbox", 'sender');
}
public function receivedMessages()
{
    return $this->hasMany("App\Inbox", 'recipient');
}

(.. , ),

$user->sentMessages

. ( , ... )

public function unreadSentMessages()
{
    return $this->hasMany("App\Inbox", 'sender')
                ->where('trashed_in_sender', 0)
                ->where('show_in_sender', 0)
                ->orderBy('created_at', 'desc');
}

$user- > sentMessages , $user- > notreadSentMessages , .

+1

Source: https://habr.com/ru/post/1692357/


All Articles