php - Eloquent and Pivot Tables in Laravel 4 -


i have poll table, students table, , pivot table between them includes token , 3 votes.

    public function students()     {         return $this->belongstomany('student', 'polls_students')->withpivot('token','first','second','third');     } 

while working out saving poll results, came across odd behavior don't quite understand. i'm hoping can explain i'm missing:

    $poll = poll::find(input::get('poll_id'));      foreach($poll->students()->where('students.id', '=', input::get('student_id'))->get() $student){         var_dump($student->pivot->token);     }      $student = $poll->students()->where('students.id', '=', input::get('student_id'))->get();     var_dump($student->pivot->token); 

in above code, foreach loop display token, second 1 throws exception undefined property: illuminate\database\eloquent\collection::$pivot

what missing? these 2 calls not logically creating same object? how 'pivot' working on first , not latter?

you first example:

$poll = poll::find(input::get('poll_id')); foreach($poll->students()->where('students.id', '=', input::get('student_id'))->get() $student){     var_dump($student->pivot->token); } 

here $poll->students() retrieves collection , because of foreach loop single object in $student variable , can use $student->pivot->token

you second example:

$student = $poll->students()->where('students.id', '=', input::get('student_id'))->get(); var_dump($student->pivot->token); 

here doing same thing, using $poll->students() getting collection time not using loop , trying same thing using $student->pivot->token it's not working because didn't define index want pivot->token, if try this

$student->first()->pivot->token 

or maybe

$student->get(1)->pivot->token 

or maybe can use first() instead of get() this

$student = $poll->students()->where('students.id', '=', input::get('student_id'))->first(); 

then can use

$student->pivot->token 

remember that, get() returns collection if there 1 record/model.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -