我是Laravel&的新手。雄辩。我基本上在我的数据库中有这些表:
用户:
优惠券:
投票(支点):
因此,用户可以对优惠券进行投票。每张优惠券属于一个用户(创建者)。在文档之后,我映射了这样的关系:
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
}
}
所以我试图映射“投票”部分。我不知道该怎么做。我不确定它是否正确:
// 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?
}
我很确定这是错的。有人可以帮帮我吗?
答案 0 :(得分:2)
我在4.2中仅使用了枢轴,但我认为5应该非常相似
id = 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]]);
希望它有效:)