dqteh7347 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 {

    //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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?