2016-11-30 13 views
0

私はここで、この機能を持っている:このWHERE句で変数を受け入れないのはなぜですか? Laravel 5.3

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) { 
        $new = DB::table('prefs')->select('id', 'tag')->where('tag', '=', $t)->get(); 
        $taguser = new Tag(array(
             'user_id' => $pref->id, 
             'tag_id' => $t, 
             'tagsid' => $new->id 
            )); 
        $taguser->save(); //save in table 
       } 
      } 
      return view('refactor'); 
    } 

それは基本的には好みのリストの中でそれを比較して、データを分割、適切に設定されていなかった古いデータベーステーブルからデータをつかみます別のテーブルを取得し、そのデータIDを取得し、タグ、ユーザID、およびプリファレンスIDをピボットテーブルに出力します。

それはそれがやるべきことです。今のところ、prefsテーブルからのidが未定義であることがわかります。その最後のビットは'tagsid' => $new->id < =明らかに存在しません。

しかし、それはすべきです。私は何を間違えたのですか?ここで

は、エラーの作品です:あなたが->get()を行うと

Undefined property: Illuminate\Support\Collection::$id 
    at HandleExceptions->handleError('8', 'Undefined property: Illuminate\Support\Collection::$id', 'C:\xampp\htdocs\Missionseek2\app\Http\Controllers\RefactorController.php', '29', array('prefs' => object(Collection), 'pref' => object(stdClass), 'tags' => '1-3,1-5,1-4,2-3,3-2,3-9,3-3,3-4,3A-5,3A-8,5-2,8-4,8-8,8-13,9-5,7A-2,7A-4,7A-10', 'tag' => array('1-3', '1-5', '1-4', '2-3', '3-2', '3-9', '3-3', '3-4', '3A-5', '3A-8', '5-2', '8-4', '8-8', '8-13', '9-5', '7A-2', '7A-4', '7A-10'), 't' => '1-3', 'new' => object(Collection))) in RefactorController.php line 29 

答えて

2

それはCollectionオブジェクトを返します。基礎となるモデルを取得するには、反復処理が必要になります。

最初に一致する結果を得るには->first()を使用する必要があり、モデル自体が返されるので、->idフィールドにアクセスできます。要するに

、この行を変更:

$new = DB::table('prefs')->select('id', 'tag')->where('tag', '=', $t)->get(); 

へ:

$new = DB::table('prefs') 
      ->select('id', 'tag') 
      ->where('tag', $t) 
      ->first(); 
関連する問題