2013-10-23 09:03



I am new to eloquent for laravel 4 and i can't quite figure out on how to make and save related models.

Table Messages: id | user | message | parent

For example:

class Message extends Eloquent {

   public function user(){
      return $this->belongs_to('User', 'id');

   public function child(){
      return $this->hasMany('Message', 'parent');

   public function parent(){
      return $this->belongs_to('Message', 'id')


So if you have a conversation you have a message, this message may or may not have a child or a parent and always has a user which made the message. So if i want to save a conversation this way, how would i do this?

For example, i have to following conversation:

John (1) says: Hi all!
Mark (3) responds: Hey there!
Hans (4) responds: Hi john
Peter(2) responds: Goodmorning.

Now i am john and i would like to save this conversation as below:

  id  |  user  |    message    | parent
1     | 1      | Hi, All!      | NULL
2     | 3      | Hey there!    | 1
3     | 4      | Hi john       | 1
4     | 2      | Goodmorning.  | 1

I can save them all separately but i figure there has to be a better way than below:

$parent = NULL;

foreach($messages as $message){
   $model = new Message;
      $model->user = $message['user'];
      $model->message = $message['value'];
         $model->parent = $parent;
      $parent = $model->id;
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dsf4354353452 dsf4354353452 8年前

    The initial problem I saw was that you are saying that the message's parent is always itself, you need to specify an additional unsigned integer to relate on. Here's one example:

    public function parent(){
        return $this->belongs_to('Message', 'parent_id')

    You need to use that same 'parent_id' for the children as well:

    public function children(){
        return $this->hasMany('Message', 'parent_id');
    点赞 评论 复制链接分享