【问题标题】:Eloquent: confusion using pivot tableEloquent:使用数据透视表混淆
【发布时间】:2016-04-11 21:38:32
【问题描述】:

我是 Laravel 和 Eloquent 的新手。我的数据库中基本上有这些表:

  • 用户:

    • 身份证
    • 电子邮件
    • 姓名
    • 密码
  • 优惠券:

    • 身份证
    • 标题
    • 详情
    • 折扣
    • user_id(创建者)
  • 投票(枢轴):

    • user_id
    • coupon_id
    • 投票

因此用户可以对优惠券进行投票。每张优惠券属于一个用户(创建者)。按照文档,我映射了这样的关系:

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?
}

我很确定这是错误的。有人可以帮帮我吗?

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    我只在 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"
        }
     }
    ]
    

    希望它有效:)

    【讨论】:

    • 就是这样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 2013-09-03
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2018-11-11
    相关资源
    最近更新 更多