Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

hi, on your category relationship on the Answer model try adding ->withPivot('points')

public function answers()
{
    return $this->belongsToMany('Answer',"scores")->withPivot('points');    
 }
0

That's strange I got this error :

An Error Was Encountered

Unknown function withPivot

Is there a way for me to check what version of Eloquent I'm using ? Maybe I need to update it

0

Shotman, your functions should look like this:

public function categories()
{
	// You can also use Category::class instead of App\Category
    return $this->belongsToMany('App\Category', "scores")
	            ->withPivot('point);
	
}

public function answers()
{
	// Again, You can also use Answer::class instead of App\Category
	return $this->belongsToMany('App\Answer',"scores")
				->withPivot('point');
}

And here is the code for accessing your pivot columns:

public function test(){
    $cat = Category::find(1);
    foreach ($cat->answers as $ans){
        var_dump($ans->pivot->point);
    }
}

public function test2(){
    $ans = Answer::find(1);
    foreach ($ans->categories as $cat){
        var_dump($cat->pivot->point);
    }
}
Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Shotman shotman Joined 2 Sep 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.