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

Ham*_*ali 6 php mysql laravel eloquent laravel-5

我正在制作一个投票系统,我有两个表:

  • pollstable : 有那些字段 ( id,question,created_at,updated_at)。

  • choicestable : 有那些字段 ( 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');
    }
}
Run Code Online (Sandbox Code Playgroud)

选择型号:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试构建此查询时,它不会返回选择:

$poll->first()->choices()->get()
Run Code Online (Sandbox Code Playgroud)

PS:与第一次投票相关的选择表中有很多选择。

小智 0

这:

public function poll()
{
  return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
}
Run Code Online (Sandbox Code Playgroud)

public function choices()
{
  return $this->BelongsToMany('App\Choice')->withPivot('ip','name','phone','comment');
}
Run Code Online (Sandbox Code Playgroud)

应该:

public function poll()
{
  return $this->belongsToMany('App\Poll')->withPivot('ip','name','phone','comment');
}
Run Code Online (Sandbox Code Playgroud)

public function choices()
{
  return $this->belongsToMany('App\Choice')->withPivot('ip','name','phone','comment');
}
Run Code Online (Sandbox Code Playgroud)