简体   繁体   中英

Eloquent and Pivot Tables in Laravel 4

I have a Poll table, a Students table, and a pivot table between them that includes a token and their three votes.

    public function students()
    {
        return $this->belongsToMany('Student', 'polls_students')->withPivot('token','first','second','third');
    }

While working out saving the poll results, I came across some odd behavior that I don't quite understand. I'm hoping somebody can explain what it is I'm missing:

    $poll = Poll::find(Input::get('poll_id'));

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

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

In the above code, the foreach loop will successfully display the token, where the second one throws the exception Undefined property: Illuminate\\Database\\Eloquent\\Collection::$pivot

What am I missing? Are these two calls not logically creating the same object? How is 'pivot' working on the first and not the latter?

You first example:

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

Here $poll->students() retrieves a collection and because of foreach loop you get a single object in your $student variable and you 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 you are doing same thing, using $poll->students() you are getting a collection but this time you are not using a loop and trying to do same thing using $student->pivot->token but it's not working because you didn't define any index from which you want to get the pivot->token , if you try something like this

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

Or maybe

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

Or maybe you can use first() instead of get() like this

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

Then you can use

$student->pivot->token

Remember that, get() returns a collection even if there is only one record/model.

$poll = Poll::find(Input::get('poll_id'));

foreach($poll->students as $student){

    var_dump($student->pivot->where('student_id',$student->id)->where('poll_id',$poll->id)->first()->token);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM