Ad

Eloquent: Confusion Using Pivot Table

- 1 answer

I'm new on Laravel & Eloquent. I basically have this tables in my db:

  • Users:

    • id
    • email
    • name
    • password
  • Coupons:

    • id
    • title
    • detail
    • discount
    • user_id (creator)
  • Votes (pivot):

    • user_id
    • coupon_id
    • vote

So users can vote on coupons. Each coupon belongs to one user (creator). Following the documentation, I mapped the relationship like this:

class Coupon extends Model
{
  public function users()
  {
    return $this->belongsTo('App\User'); // A coupon belongs to one user
  }
}

class User extends Model
{
  public function coupons()
  {        
    return $this->hasMany('App\Coupon'); // A user has many coupons
  }
}

So I'm trying to map the "votes" part. I don't know how to do that. I'm not sure if it is right:

// User class
public function votes()
{        
    return $this->belongsToMany('App\Coupon', 'votes'); // A coupon vote belongs to many users?
}

// Coupon class
public function votes()
{        
    return $this->belongsToMany('App\User', 'votes'); // A user vote belongs to many coupons?
}

I'm pretty sure this is wrong. Can somebody help me?

Ad

Answer

I only used pivots in 4.2 but I think 5 should work pretty similar

class Coupon extends Model
{
  public function coupon_votes()
  {
    return $this->belongsToMany('App\User', 'votes', 'user_id', 'coupon_id')->withPivot('vote');
  }
}

class User extends Model
{
  public function coupon_votes()
  {        
     return $this->belongsToMany('App\Coupon', 'votes', 'coupon_id', 'user_id')->withPivot('vote');
  }
}

Saving:

//add a vote 1 four coupon_id 2 
$user->coupon_votes()->attach(2, ['vote' => 1]);
//or multiple - add vote 1 for coupon_id 2 and vote 0  for coupon_id 3
$user->coupon_votes()->sync([2 => ['vote' => 1], 3 => ['vote'=> 0]]);

Retrieving

$user->coupon_votes()->get();

[
  {
    id: "2",
    // ... <-coupon info 
    pivot: {
      user_id: "1",
      coupon_id: "2",
      vote: "1"
    }
  },
  {
    id: "3",
    // ... <-coupon info 
    pivot: {
      user_id: "1",
      coupon_id: "3",
      vote: "0"
    }
  }
]

$coupon  = Coupon::find(2);

$coupon->coupon_votes()->get()

[
 {
  id: "1",
  // ... <- user info
  pivot: {
      coupon_id: "2",
      user_id: "1",
      vote: "1"
    }
 }
]

Hope it works :)

Ad
source: stackoverflow.com
Ad