我有它,以便在创建新分支时,该名称变成一个用于查询的子对象,但是当我更新记录时,子对象变量保持不变,有没有办法让它在记录更改时自动更新?
class Branch extends \Eloquent {
public static $rules = [
'name' => 'required'
];
protected $fillable = ['name', 'slug'];
protected function setNameAttribute($name)
{
$this->attributes['name'] = $name;
$this->attributes['slug'] = Str::slug($name);
}
}
在我的控制器中
public function update($slug)
{
$branch = Branch::whereSlug($slug);
$validator = Validator::make($data = Input::except('_method', '_token'), Branch::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$branch->update($data);
return Redirect::route('branches.index');
}
首先,如果模型事件是您要处理的Eloquent模型,则模型事件应该加入到mutator中,而Fluent查询构建器则不会。我认为这Branch::whereSlug($slug)
将返回Fluent查询生成器-只需检查是否Branch::whereSlug($slug)->firstOrFail()
可行即可。我认为可能会。
如果不这样做,我建议您选择两个选项-首先,Colin Viebrock具有出色的软件包,可以很方便地生成弹头。
如果您想自制软件,则可以boot
使用模型事件将其放入方法中:
public static function boot() {
static::saving( function( $model ) {
$model->name = $model->name; // force the slug to be rebuilt
} );
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句