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');
}
}
:
$user->coupon_votes()->attach(2, ['vote' => 1]);
$user->coupon_votes()->sync([2 => ['vote' => 1], 3 => ['vote'=> 0]]);
$user->coupon_votes()->get();
[
{
id: "2",
pivot: {
user_id: "1",
coupon_id: "2",
vote: "1"
}
},
{
id: "3",
pivot: {
user_id: "1",
coupon_id: "3",
vote: "0"
}
}
]
$coupon = Coupon::find(2);
$coupon->coupon_votes()->get()
[
{
id: "1",
pivot: {
coupon_id: "2",
user_id: "1",
vote: "1"
}
}
]
, :)