我正在制作一个投票系统,我有两个表:
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:与第一次投票相关的选项表中有很多选项。
最佳答案
在这种情况下你有 Many To Many 关系,所以尝试更改 belongsTo
in :
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:您想要带有时间戳的数据透视表 create_at,updated_at
正如您在 OP 中提到的那样,因此您必须使用 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();
希望这对您有所帮助。
关于php - Laravel 5 使用具有许多关系的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547060/