简体   繁体   English

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

[英]Laravel Eloquent ORM: trouble with one-to-many using belongs_to()

I'm having trouble accessing a relationship in Laravel. 我在Laravel中访问关系时遇到问题。 Relevant to this question, I have two tables, messages and users . 关于这个问题,我有两个表, messagesusers

The messages table looks like: messages表如下所示:

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

The users table looks like: users表如下所示:

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. user_fromuser_to列都是整数,它们与发送消息或消息发送给的用户的id (主键)相对应。

The relevant portion of my Message model looks like: 我的Message模型的相关部分如下所示:

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: 我的User模型的相关部分如下所示:

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. 引发错误Trying to get property of non-object I know the $message object is defined because all other properties except user_from and user_to are defined and print out perfectly. 我知道$message对象已定义,因为除user_fromuser_to以外的所有其他属性均已定义并完美打印。 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();

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. Message模型from_user()to_user()而不是user_from()user_to()更改方法名称(并更改视图以使其对应)完全解决了该问题。 No other code was changed. 没有其他代码被更改。

Laravel fetches the database field over the method name, when you specify a custom field (I think). 当您指定自定义字段时(我认为),Laravel会通过方法名称获取数据库字段。 Weird. 奇怪的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM