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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀