简体   繁体   中英

Insert relational models laravel eloquent

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 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'];
      if(!is_null($parent)){
         $model->parent = $parent;
      }
   $model->save();
   if(is_null($parent)){
      $parent = $model->id;
   }
}

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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