我正在制作民意调查系统,我有两张桌子:
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:与第一轮投票相关的选择表中有很多选择。
答案 0 :(得分:1)
在这种情况下,您有 Many To Many 关系,因此请尝试更改$scope.cancel = function () {
$uibModalInstance.close();
};
:
belongsTo
致public function poll()
{
return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
}
,它将是:
belongsToMany
注1:您必须将public function poll()
{
return $this->belongsToMany('App\Poll')->withPivot('ip','name','phone','comment');
}
更改为BelongsToMany
,请注意belongsToMany
应为小写。
注2:您希望数据透视表中包含时间戳B
,如您在OP中提到的那样,您必须使用create_at,updated_at
:
withTimestamps();
希望这有帮助。
答案 1 :(得分:0)
此:
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');
}