具有命名空间的Laravel多态投票系统

时间:2014-12-23 07:05:53

标签: laravel laravel-4 eloquent

我试图在帖子和评论中添加我希望的简单投票模块。 “连接”是我的应用程序中的一种帖子。用户可以向上或向下对联系或评论进行投票。

我遇到的问题是当我尝试将投票附加到Connection时。我收到此错误:Class name must be a valid object or a string

以下是有问题的代码行:

$voteToCast = $vote->voteable()->associate($voteable);

我确信$ voteable var是一个Ardent / Eloquent模型的实例,所以我只能假设错误在于我命名我的模型的方式,或者一些可怜的错误我太盲目了看到。任何帮助将不胜感激。

谢谢!

连接模型(帖子类型):

...

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

投票模型:

/* Votes Model */

namespace Acme\Votes;

use Illuminate\Database\Eloquent\Model;
use LaravelBook\Ardent\Ardent;

class Vote extends Ardent {

    protected $table = 'votes';

    protected $fillable = [
        'value',
        'votable_id',
        'voteable_type'
    ];

    /**
     * Establish the polymorphic relationship
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function voteable()
    {
        return $this->morphTo();
    }

    public function users()
    {
        return $this->belongsTo('Acme\\Users\\User');
    }

    /**
     * Vote the item up
     *
     * @param Model $voteable
     * @return mixed
     */
    public static function up(Model $voteable)
    {
        return (new static)->cast($voteable, 1);
    }

    /**
     * Vote the item down
     *
     * @param Model $voteable
     * @return mixed
     */
    public static function down(Model $voteable)
    {
        return (new static)->cast($voteable, -1);
    }

    /**
     * Execute the vote
     *
     * @param Model $voteable
     * @param int $value
     * @return bool
     */
    protected function cast(Model $voteable, $value = 1)
    {
        if (!$voteable->exists) return false;

        $vote = new static;
        $vote->value = $value;

        $voteToCast = $vote->voteable()->associate($voteable);
        $voteToCast->save();
    }

    /**
     * Restrict the votes so the absolute value is 1
     *
     * @param $value
     */
    public function setValueAttribute($value)
    {
        $this->attributes['value'] = ($value == -1) ? -1 : 1;
    }
}

投票控制人:

...

public function cast($connection)
{

    $voteable = Connection::findOrFail($connection);

    if (Input::get('value' < 1)){
        return Vote::down($voteable);
    }

    return Vote::up($voteable);

}

1 个答案:

答案 0 :(得分:0)

经过一些更多的故障排除后,这似乎与Ardent处理关系的方式有关。我能够在我的投票模型上使用Eloquent而不是Ardent,投票机制现在可以完美运行。