我有一个创建错误报告系统的“票证”表。此票证有一个enum status列,即open、close或solved。
我不想在控制器内打开/关闭/求解票证,我只想在模型中这样做;也就是说,我希望有名为open()、close()和solved()的函数,这样我就可以转到Ticket::find($id)->close();了。这应该将属性status设置为close,然后保存它!
做这件事最好的方法是什么?此外,这会否被视为不良做法?我应该在控制器内这样做吗?
我试过这样做,但没有成功:
public function close()
{
$this->status = 'close';
// Also tried $this->attributes['status'] = 'close';
$this->save();
}发布于 2014-09-19 21:06:29
这是一个完美的模式,国际海事组织。
class Ticket extends Eloquent {
public function open() {
$this->status = 'open';
$this->save();
}
}发布于 2014-09-19 20:57:55
在我看来,这是一种比直接从controller中直接执行的更好的方法,您可以为此使用scopeMethod,例如:
function scopeClose($query)
{
// Close the ticket and return $query;
return $query->where('...');
}如果返回$query,则可以执行方法链接。例如:
Ticket::find($id)->close()->otherMethodCall();例如,如果您执行query,那么$query->update('...')返回$query就没有任何意义,因为它将是update方法的结果,也就是true/false。
使用scope方法的好处是:
// In your model
function scopeClose($query, $id)
{
$model = $query->find($id);
$model->status = 'whatever';
$model->save();
return true; // Or just return $model->save();
}所以您可以在您的controller中使用
Ticket::close(10); // Update the status of record with id 10发布于 2018-04-12 19:32:23
另一种方法是使用update()函数,但在这样做之前,您必须确保要更新的列确实在$fillable数组中。
//make sure in fillable
protected $fillable = [
'status',
];
// ...
// In your model
public function close()
{
$this->update([
$this->status = 'close';
]);
}干杯。
https://stackoverflow.com/questions/25942173
复制相似问题