douhua1890 2013-10-23 09:03
浏览 66
已采纳

插入关系模型laravel雄辩

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

1条回答 默认 最新

  • dsf4354353452 2013-11-08 15:31
    关注

    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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。