dongzhang8680 2014-01-18 08:33
浏览 96
已采纳

Laravel 4,PHP将每个Hashtag保存在一个DB Row中

I am trying to save hashtags to a database. At the moment they are saved in a single row with the image_id and the following format:

Hashtags:    #test bla #test #test

DB:    test,test,test

What do I have to do to save every single hashtag in a single database row maintaining the correstpondig photo_id?

Here is how I save the hashtags:

$hashtag = new Hashtag;

  $hashtag->photo_id = $photo->id;

      $hashtag_string = Input::get('hashtags');




        $str = $hashtag_string;

            preg_match_all('/#([^\s]+)/', $str, $matches);

        $hashtags_final = implode(',', $matches[1]);




$hashtag->hashtag = $hashtags_final;
$hashtag->save();
  • 写回答

1条回答 默认 最新

  • dseomy1964 2014-01-18 09:41
    关注

    Depending on your needs there is several solutions:

    First: you can loop through hashtags and save them with correct image_id. like this:

    $hashtag_string = Input::get('hashtags');
    
    preg_match_all('/#([^\s]+)/', $hashtag_string, $matches);
    
    //looping through matched items in your $matches array
    foreach($matches as $tag)
    {
      $hashtag = new Hashtag();
      $hashtag->image_id = $photo->id;
      $hashtag->hashtag = $tag;
      $hashtag->save();
    }
    

    Second: create Many-to-Many type of relation between Image and Hashtag and use full power of it. You can find everything in the oficial docs on creating and using

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程