Mortada Jafar
Mortada Jafar

Reputation: 3679

Laravel 5.2 relationship with pivot table

my tables:

tables

  1. every part contain many of card.
  2. every card belong to many of part.

now,using laravel eloquent model how can fetch all card for a part without add more column to database

Upvotes: 0

Views: 526

Answers (2)

z3r0ck
z3r0ck

Reputation: 683

You need to define your relationships like below:

class Part extends Model
{
    public function cards()
    {
        return $this->belongsToMany('App\Cards', 'user_cards');
    }
}

Then you can fetch all the cards for a part like below:

$cards = Part::with('cards')->find($part_id);

Upvotes: 1

abhishek.agarwal
abhishek.agarwal

Reputation: 36

Part::whereHas('cards', function($query) use ($cardId){
  $query->where('id', $cardId);  
})->get();

And your model relation should contain like this, for Part.php

public function cards(){ 
 return $this->belongsToMany('App\Card');    
}

And for Card.php

public function parts(){ 
 return $this->belongsToMany('App\Part');    
}

Upvotes: 0

Related Questions