dqteh7347
2013-06-06 17:54
采纳率: 100%
浏览 84
已采纳

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 {

    //relationships
    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 {

    //relationships
    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条回答 默认 最新

  • dpc46827 2013-06-06 18:24
    已采纳

    Making the method names in the Message model from_user() and to_user() instead of user_from() and user_to() (and changing the view to correspond) fixes the problem completely. No other code was changed.

    Laravel fetches the database field over the method name, when you specify a custom field (I think). Weird.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题