【问题标题】:Polymorphic Relation voteable多态关系可投票
【发布时间】:2018-07-28 08:58:33
【问题描述】:

我对 cme​​ts 和帖子的投票有一些问题。我希望你能帮助我。

我希望允许用户对帖子和 cmets 进行上下投票。

我的人际关系是这样的:

投票:

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:插入投票(value、voteable_id、voteable_type、updated_at、created_at)值(1、1、App \发布,2018-02-17 16:58:58,2018-02-17 16:58:58)) ......

【问题讨论】:

  • 你的表名是错误的“votes”而不是“voteables”!
  • 没错,但我告诉模型该表称为“可投票”。为什么这不起作用? public function votes() { return $this->morphMany('App\Vote', 'voteable'); }
  • 如果我在 'votes' 中重命名表,我会收到错误:SQLSTATE[42S02]: Base table or view not found: 1146 Table 'votes.votes' doesn't exist....

标签: laravel relationship vote


【解决方案1】:

By default convention,名为Vote 的模型将映射到名为votes 的表。由于您使用voteables 作为表名,因此您需要告诉模型新的表名应该是什么。

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

或者,您可以将表从 voteables 重命名为 votes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多