繁体   English   中英

多态关系可投票

[英]Polymorphic Relation voteable

我对评论和帖子的投票有些疑问。 我希望你能帮助我。

我想允许用户上下投票。

我的关系如下所示:

投票:

class Vote extends Model{
protected $fillable= ['value', 'user_id', 'voteable_type', 'voteable_id'
];

public function voteable()
{
    return $this->morphTo();
}

}

可投票:

public function up()
{
    Schema::create('voteables', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('voteable_id');
        $table->string('voteable_type');
        $table->integer('value');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

发表和评论模型:

public function votes()
{
    return $this->morphMany('App\Vote', 'voteable');
}

我是否仍需要与用户保持联系,以便查看用户是否已投票?

public function isvotedBy(User $user)
{
    return $user->votes()
        ->where('user_id', $user->id)
        ->exists();
}

如何保存用户的投票? 我已经试过了:

public function storeVotePostUp(Post $post)
{

    $post->votes()->create([ 'value' => '1' ]);

{

但我收到一条错误消息:

SQLSTATE [42S02]:找不到基表或视图:1146表'DBName.votes'不存在(SQL:插入选票(值,voteable_id,voteable_type,updated_at,created_at)值(1、1,App \\ Post, 2018-02-17 16:58:58,2018-02-17 16:58:58))......

默认情况下惯例 ,一个名为模型Vote将映射到表名为votes 由于您使用可voteables作为表名,因此需要告诉模型新表名应为什么。

class Vote extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'voteables';
}

或者,你可以从你的重命名表voteablesvotes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM