Laravel 5使用具有hasMany关系的数据透视表


Laravel 5 using pivot table with hasMany relationship

我正在制作一个轮询系统,我有两个表:

  • polls表:具有这些字段(id,question,created_at,updated_at)。

  • choices表:具有这些字段(id,poll_id,choice)。

一个名为choice_poll的数据透视表:具有这些字段(id,choice_id,poll_id,ip,name,phone, comment ,created_at,updated_at

轮询模型:

class Poll extends Model 
{
    protected $table = 'polls';
    protected $fillable = ['question'];
    public $timestamps = true;
    public function choices()
    {
      return $this->BelongsToMany('App'Choice')->withPivot('ip','name','phone','comment');
    }
}

选择模型:

class Choice extends Model 
{
    protected $table = 'choices';
    protected $fillable = ['poll_id','choice'];
    public $timestamps = false;
    public function poll()
    {
      return $this->belongsTo('App'Poll')->withPivot('ip','name','phone','comment');
    }
}

现在,当我尝试构建这个查询时,它不会返回选项:

$poll->first()->choices()->get()

PS:在与第一次轮询相关的选项表中有许多选项。

在这种情况下,您有多对多关系,因此尝试更改中的belongsTo

public function poll()
{
    return $this->belongsTo('App'Poll')->withPivot('ip','name','phone','comment');
}

belongsToMany,它将是:

public function poll()
{
    return $this->belongsToMany('App'Poll')->withPivot('ip','name','phone','comment');
}

注意1:您必须将BelongsToMany更改为belongsToMany,注意B应为小写。

注意2:您想要如您在OP中提到的具有时间标记create_at,updated_at的数据透视表,因此您必须使用withTimestamps();:

return $this->belongsToMany('App'Poll')
            ->withPivot('ip','name','phone','comment')
            ->withTimestamps();
//AND in the other side also
return $this->belongsToMany('App'Choice')
            ->withPivot('ip','name','phone','comment')
            ->withTimestamps();

希望这能有所帮助。

这:

public function poll()
{
  return $this->belongsTo('App'Poll')->withPivot('ip','name','phone','comment');
}

public function choices()
{
  return $this->BelongsToMany('App'Choice')->withPivot('ip','name','phone','comment');
}

应该是:

public function poll()
{
  return $this->belongsToMany('App'Poll')->withPivot('ip','name','phone','comment');
}

public function choices()
{
  return $this->belongsToMany('App'Choice')->withPivot('ip','name','phone','comment');
}