在为模型定义构造函数时,Laravel 5.3软删除不起作用

Ama*_*man 1 model laravel laravel-5

我的模型测试如下

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';
    }
}
Run Code Online (Sandbox Code Playgroud)

我确保test_stage表中有一个'deleted_at'列.但软删除不起作用.使用delete()方法永久删除表中的记录.作为验证的附加步骤,我手动为某些列添加了"deleted_at"值.但查询模型仍然给我软删除记录.

此外,完全删除模型构造函数,并使用以下命令定义表名:

protected $table = 'test_stage';
Run Code Online (Sandbox Code Playgroud)

奇迹般有效!那是软删除神奇地再次开始工作.

或者有没有办法根据环境定义表名而无需定义构造函数?

Sto*_*mer 6

我认为问题可能是你要覆盖设置的构造函数Illuminate\Database\Eloquent\Model.你有没有尝试过

   public function __construct(array $attributes = []) {
       parent::__construct($attributes);
       if (!\App::environment('production')) {
           $this->table='test_stage';
       }
   }  
Run Code Online (Sandbox Code Playgroud)

编辑:更详细的解释

当你覆盖constructor你正在扩展的类时,原来不再被执行了.这意味着不能执行雄辩模型的必要功能.看到constructorIlluminate\Database\Eloquent\Model如下:

/**
 * Create a new Eloquent model instance.
 *
 * @param  array  $attributes
 * @return void
 */
public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}
Run Code Online (Sandbox Code Playgroud)

通过确保扩展类需要构造函数为相同的参数扩展类和执行 parent::__construct($attributes);第一,constructor中的扩展类中最先被执行.之后,您可以$this->table扩展类中覆盖.