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.

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

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面