我有一个 Question 模型,它与 Answer 模型具有一对多关系。
现在我想为这两个模型添加赞成票/反对票功能,我是否需要创建两个表,如 VotesQuestions 和 VotesAnswers,或者我可以用一个来管理吗?如果是,怎么办?
最佳答案
您可以使用多态关系。这是 Laravel 内置的。文档是 here .此处显示的代码适用于 Laravel 4,但功能与 Laravel 5 相同。
创建一个投票表,并确保它至少有两个特定字段:votable_id 和 votable_type。在数据库迁移中,您将使用语句 $table->morphs('votable');
,它会创建两个字段。您可以拥有任意数量的其他字段,但为了确保关系有效,这两个字段是必需的。
接下来,设置具有投票关系的投票模型。此关系的名称应与您创建的字段的基本名称相匹配:
class Vote extends Eloquent {
public function votable() {
return $this->morphTo();
}
}
通过此设置,您现在可以将投票关联到您想要的任何模型。继续将投票关系添加到问答模型中:
class Question extends Eloquent {
public function votes() {
return $this->morphMany('Vote', 'votable');
}
}
class Answer extends Eloquent {
public function votes() {
return $this->morphMany('Vote', 'votable');
}
}
您现在可以通过关系访问任何问题/答案的投票:
$q = Question::first();
$qVotes = $q->votes; // Collection of votes for the question.
$a = Answer::first();
$aVotes = $a->votes; // Collection of votes for the answer.
如果您需要,您还可以通过投票获得相关的问答模型:
$v = Vote::first();
$vRelated = $v->votable; // Will automatically be a Question or Answer object, depending on what the vote was for.
关于php - Laravel,我需要多个数据库表来对不同模型进行投票吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29222441/