【问题标题】:Laravel 5.3 soft deletes not working when defining a constructor for the model为模型定义构造函数时,Laravel 5.3 软删除不起作用
【发布时间】:2018-03-19 13:42:39
【问题描述】:

我有一个模型测试如下

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';

像魅力一样工作!那是软删除神奇地重新开始工作。

或者有什么办法可以根据环境定义表名而不需要定义构造函数?

【问题讨论】:

    标签: laravel laravel-5 model


    【解决方案1】:

    我认为问题可能是您正在覆盖在Illuminate\Database\Eloquent\Model 中设置的构造函数。你试过了吗

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

    编辑:更详细的解释

    当您覆盖您正在扩展的类的constructor 时,原来的不再被执行。这意味着 eloquent 模型的必要功能不会被执行。请参阅下面的constructor Illuminate\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);
    }
    

    通过确保 extending 类需要与 extended class 相同的构造函数参数并首先执行 parent::__construct($attributes);constructor扩展的 类首先被执行。之后,您可以在扩展类中覆盖$this->table

    【讨论】:

    • @RafaelBerro 已更新。希望我的答案现在更清楚了。
    • @Stormhammer 哇!这正是正在发生的事情。我对类似的事情持怀疑态度,但错过了正确的方向。
    猜你喜欢
    • 2017-10-16
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    相关资源
    最近更新 更多