Laravel 4 Relationship: a message belong to two user

帅比萌擦擦* 提交于 2019-12-05 08:07:05

问题


I am making user to user messaging system in laravel 4. So in a simplified version i have to table

First table

Users

user_id | user_name

Second table

Messages

message_id | message_from_user_id | message_to_user_id | message_content |

So after reading the documentation I learned that User has many message and message belongs to User.

But how do I actually relate them in coding?

I am quite confused how will I use the foreign key in this case for a message that will have two user?


回答1:


Check this out: http://laravel.com/docs/eloquent#many-to-many

Basically you need a table structure like this

Users: id | username

Messages: id | from | content

user_messages: user_id | message_id


You can define your models like this

class User extends Eloquent {

    public function messages()
    {
        return $this->belongsToMany('Message');
    }

    public function sent_messages()
    {
        return $this->hasMany('Messages', 'from');
    }

}

class Message extends Eloquent {

    public function from()
    {
        return $this->belongsTo('User', 'from');
    }

    public function to()
    {
        return $this->belongsToMany('User');
    }
}


来源:https://stackoverflow.com/questions/18716784/laravel-4-relationship-a-message-belong-to-two-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!