简体   繁体   中英

Polymorphic Relation voteable

I have some problems with the voting of comments and posts. I hope you can help me.

I want to allow users to vote posts and comments up or down.

My relationships look like this:

Vote:

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

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

}

Voteable:

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');
    });
}

Post and Comment Model:

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

Do I still need a relationship with the user so I can see if the user has voted?

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

How can I save a vote from a user? I have tried this:

public function storeVotePostUp(Post $post)
{

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

{

But i get a error Message:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'DBName.votes' doesn't exist (SQL: insert into votes (value, voteable_id, voteable_type, updated_at, created_at) values (1, 1, App\\Post, 2018-02-17 16:58:58, 2018-02-17 16:58:58)) ......

By default convention , a model named Vote will map to a table named votes . Since you are using voteables as the table name, you need to tell your model what the new table name should be.

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

Alternatively, you can rename your table from voteables to votes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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