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

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();

我正在尝试将主题标签保存到数据库中。 目前,它们使用image_id和以下格式保存在一行中: p>

  Hashtags:#test bla #test #test 
 
DB:test,test,  test 
  code>  pre> 
 
 

如何在保留correstpondig photo_id的单个数据库行中保存每个主题标签? strong> p>

以下是我保存主题标签的方法: p>

  $ hashtag = new Hashtag; 
 
 $ hashtag-> photo_id = $ photo-&gt  ; 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(); 
  code>  pre> 
  div>

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