我有一个模型测试如下
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Test extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function __construct() {
if (!\App::environment('production')) {
$this->table='test_stage';
}
}
我已确保我的 test_stage 表中有一个“deleted_at”列。但是软删除不起作用。使用 delete() 方法从表中永久删除记录。作为验证的附加步骤,我为某些列手动添加了“deleted_at”值。但是查询模型仍然给我软删除的记录。
此外,完全删除模型构造函数并简单地使用以下方法定义表名:
protected $table = 'test_stage';
像魅力一样工作!那是软删除神奇地重新开始工作。
或者有什么办法可以根据环境定义表名而不需要定义构造函数?
最佳答案
我认为问题可能是您正在覆盖 Illuminate\Database\Eloquent\Model
中设置的构造函数。你试过了吗
public function __construct(array $attributes = []) {
parent::__construct($attributes);
if (!\App::environment('production')) {
$this->table='test_stage';
}
}
编辑:更详细的解释
当您覆盖要扩展的类的 constructor
时,原来的不再执行。这意味着 eloquent 模型的必要功能不会被执行。请参阅下面的 Illuminate\Database\Eloquent\Model
的 constructor
:
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
* @return void
*/
public function __construct(array $attributes = [])
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
通过确保 extending 类需要与 extended class 相同的构造函数参数并执行 parent::__construct($attributes);
首先执行 extended 类的 constructor
。之后,您可以覆盖 扩展类中的 $this->table
。
关于为模型定义构造函数时,Laravel 5.3 软删除不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49364469/