簡體   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