Eloquent: confusion using a pivot table

I am new to Laravel and Eloquent. I basically have these tables in my db:

  • Users

    • ID
    • Email
    • name
    • password
  • bon:

    • ID
    • title
    • the details
    • discount
    • user_id (creator)
  • Votes (turn):

    • user_id
    • coupon_id
    • Voting

This way, users can vote on coupons. Each coupon belongs to one user (creator). Following the documentation, I mapped the relationships as follows:

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 display part of the votes. I do not know how to do that. I am not sure if this is correct:

// 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 am sure this is wrong. Can someone help me?

+4
source share
1 answer

4.2, , 5 .

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');
  }
}

:

//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]]);

$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"
    }
 }
]

, :)

+2

Source: https://habr.com/ru/post/1623270/


All Articles