2013-06-06 17:54
采纳率: 100%
浏览 88

Laravel Eloquent ORM:使用belongs_to()进行一对多的麻烦

I'm having trouble accessing a relationship in Laravel. Relevant to this question, I have two tables, messages and users.

The messages table looks like:

Messages: id, user_from, user_to, read, message, created_at, updated_at

The users table looks like:

Users: id, email, password, name, created_at, updated_at, bio, reputation, last_login_ip, last_seen, active

The user_from and user_to columns are both ints that correspond to the id of the user (primary key) that sent the message or who the message was sent to.

The relevant portion of my Message model looks like:

class Message extends Eloquent {

    public function user_from() {
        return $this->belongs_to('User', 'user_from');

    public function user_to() {
        return $this->belongs_to('User', 'user_to');

The relevant portion of my User model looks like:

class User extends Eloquent {

    public function messages_from() {
        return $this->has_many('Message', 'user_from');

    public function messages_to() {
        return $this->has_many('Message', 'user_to');

In a view, I'm trying to access the user that wrote a message, writing code that looks like:

{{ $message->user_from->name }}

Which throws an error Trying to get property of non-object on that one line. I know the $message object is defined because all other properties except user_from and user_to are defined and print out perfectly. I've read through the documentation several times and I can't figure out what I have done wrong here... does anyone stick out to anyone? This seems like a textbook example but it doesn't work.

The way I've passed the data to the view is:

$messages = Message::where('user_to', '=', Auth::user()->id)->take(20)->get();

1条回答 默认 最新

相关推荐 更多相似问题