【问题标题】:Laravel: SoftDeletes doesnt work when I add $appends fieldLaravel:当我添加 $appends 字段时,SoftDeletes 不起作用
【发布时间】:2017-04-03 17:50:37
【问题描述】:

我有一个带有 softdeletes 的模型,如果我添加 A appends 字段,我的 sofdeletes 实现不起作用,有人知道发生了什么吗?

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class Users extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $table = 'users';

    protected $appends = ['assigned'];

    protected $fillable = ['category_id'];

    public function __construct()
    {
        $this->assigned = false;
    }

    public function setAssignedAttribute($value)
    {
        $this->attributes['assigned'] = $value;
    }

    public function getAssignedAttribute($value)
    {
        return $value;
    }
}

【问题讨论】:

标签: laravel eloquent


【解决方案1】:

这不是您的附加字段。是您的构造函数没有调用父构造函数,这会引导您的软删除特征。将parent::__construct() 添加到您的构造函数中。它也应该与父母的签名相匹配,所以它应该是:

public function __construct(array $attributes = [])
{
    $this->assigned = false;

    parent::__construct($attributes);
}

【讨论】:

    【解决方案2】:

    您误读了文档,您的访问者没有正确的名称:

    use Illuminate\Database\Eloquent\Model;
    
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class Users extends Model
    {
        use SoftDeletes;
    
        protected $dates = ['deleted_at'];
    
        protected $table = 'users';
    
        protected $appends = ['assigned'];
    
        protected $fillable = ['category_id'];
    
        public function __construct()
        {
            $this->assigned = false;
        }
    
        public function setIsAssignedAttribute($value)
        {
            $this->attributes['assigned'] = $value;
        }
    
        public function getIsAssignedAttribute($value)
        {
            return $value;
        }
    }
    

    你需要Is,即使它不是变量名的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 2019-12-25
      • 2018-08-14
      • 2021-03-22
      相关资源
      最近更新 更多