laravel-4 – Laravel 4 – 模型未被保存

有这个代码:

class SearchIndex extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'searchindex';

    //no timestamps
    public $timestamps = false;

    //mass-assignment
    public $fillable = array('url', 'content', 'version', 'digest');
    public $guarded = array();

    public static function updateIndex($url, $version, $content)
    {
        self::retrieveSearchEntry($url, $version)->updateContent($content)->save();
    }

    public static function retrieveSearchEntry($url, $version)
    {
        try
        {
            return self::withoutContent()->where('url', $url)->where('version', $version)->firstOrFail(array('url', 'version', 'digest'));
        }
        catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e)
        {
            return new SearchIndex(array('url' => $url, 'version' => $version));
        }
    }

    public function updateContent($content)
    {
        $hash = md5($content);
        if (!isset($this->digest) || ($this->digest != $hash))
        {
            $this->content = $content;
            $this->digest = $hash;
        }
        return $this;
    }

    public static function search($content)
    {

    }
}

如果我调用updateIndex提供url版本的新组合,则会创建一个条目.
如果我调用updateIndex提供现有的url版本对,则不会使用新内容更新该条目.我发现它与我省略’内容’字段的事实有关(原因:很大,我想设置它,而不是在那个函数中得到它).

问题:我怎样才能获取内容字段,但能够在保存时设置它?

最佳答案 解决了.原因:在firstOrFail()中进行自定义选择时,我没有选择“id”字段.以这种方式,id为null并且生成的SQL尝试更新(因为它是一个存在的对象)“其中id为NULL”,这将影响0行.

点赞