Pivot table relationship

Viewed 26

I have Category - Course pivot table. it's called Directions:

public $table = 'directions';

protected $fillable = [
    'course_category_id','course_id'
];

category:

public function manyCourses()
{
    return $this->belongsToMany(Direction::class, 'directions', 'course_category_id', 'course_id');
}

course:

public function manyCategories()
{
    return $this->belongsToMany(Direction::class, 'directions', 'course_id', 'course_category_id');
}

and in blade i'm trying to get data from directions table but i'm getting error Syntax error or access violation: 1066 Not unique table/alias I searched error and it's telling that i have relationships problem... but i think i'm doing something wrong in blade...

<select class="many-course-category" name="categoryId" multiple="multiple">
    @foreach ($c->manyCategories as $category)
        <option value="{{ $category->pivot->course_category_id }}">
            {{ $category->pivot->course_category_id->name }}
        </option>
    @endforeach
</select>

$c is my current course / course edit...

so whats i'm doing wrong ?

1 Answers

You're declaring the relationship wrong. The syntax is

belongsToMany($related, $table, $foreignPivotKey, $relatedPivotKey)

$related is not the pivot model, it's the related model.

To specify the pivot model's class, you need to chain the using() method to your relationship. (Documentation). You might need to make your Direction model extend Pivot instead of Model in its declaration (class Direction extends Pivot)

Specifying a pivot model is optional.

public function manyCourses()
{
    return $this->belongsToMany(Course::class, 'directions', 'course_category_id', 'course_id')
                ->using(Direction::class);
}
public function manyCategories()
{
    return $this->belongsToMany(Category::class, 'directions', 'course_id', 'course_category_id')
                ->using(Direction::class);
}

As for the blade part, like Erich suggested, the solution is to call $category->name.

 @foreach ($c->manyCategories as $category)
    <option value="{{ $category->pivot->course_category_id }}">
        {{ $category->name }}
    </option>
@endforeach
Related