2016-11-23 15 views
0

我正在做一個數據庫重構,將數據移動到數據透視表並創建適當的關係。這是一個古老的數據庫,所以有儲存的一些有趣的選擇......事情是這樣的:如何將這些爆炸數據移動到另一個表格中? Laravel 5.3

enter image description here

沒錯這就是好開心。無論如何,我對Laravel如何做它的對象和數組仍然有點不安,這對我來說仍然很瘋狂。所以我在這裏有這個疑問,這是一個半:

public function move() { 

     $prefs = DB::table('users')->select('id', 'Preferences')->where('Preferences', '!=', '')->get(); 

      foreach ($prefs as $pref) { 
       $tags = $pref->Preferences; 
       $tag = explode(',', $tags); 
       print_r('$tag'); 
      } 

[解決小問題]現在的print_r只是打印$標籤$標籤$標籤$標籤。我知道這跟我搞混了我對laravel如何與數組一起工作的理解。那麼我該如何做到這一點呢?

我的目標是通過每個用戶,抓住他們的標籤,爆炸這些標籤,然後將其打印到user_id旁邊的數據透視表(tag_user)。

注意:標籤包含在首選項列中,如上圖所示。

編輯:

用於存儲代碼將看起來像這樣的表:

id | tag_id | user_id 

因爲有很多更多的重構做,我就必須弄清楚如何處理鏈接下一個。在print_r('$tag')

回答

1

您需要在控制檯php artisan make:model Tag中爲user_tag表製作模型。在模型:

class Tag extends Model 
{ 
protected $table = 'tag_user'; //this is name of table in your DB 
protected $fillable = ['user_id','tag_id']; //this for mass assingment 
... 
... 
... 
} 

,然後插入新行:

public function move() { 

     $prefs = DB::table('users')->select('id', 'Preferences')->where('Preferences', '!=', '')->get(); 

      foreach ($prefs as $pref) { 
       $tags = $pref->Preferences; 
       $tag = explode(',', $tags); 
       foreach ($tag as $t) { 
        $taguser = new Tag(array(
             'user_id' => $pref->id, 
             'tag_id' => $t 
            )); 
        $taguser->save(); //save in table 
       } 
      } 
} 
1

問題刪除單引號:print_r($tag)

+0

好點的print_r。我相信每個標籤都應該創造一個新的行。 – Mugluck

1

當您使用在打印單引號,PHP將打印完全字符串,它不會評估字符串中的變量。從print_r中刪除引號。

注:與雙引號的,當他們在 單引號的字符串出現定界符語法,變量和特殊字符 轉義序列不會被擴大。

+0

解決了這個問題,謝謝。 – Mugluck

相關問題