【问题标题】:Laravel 5.4: Eloquent sync() not using model's mutator or attribute casting?Laravel 5.4:Eloquent sync() 不使用模型的 mutator 或属性转换?
【发布时间】:2017-04-27 09:10:36
【问题描述】:

Mutators and Attribute Casting

我有一个带有“修改”属性的模型。 该模型使用一组属性。这是因为存储是布尔值,但属性是通过选择管理的(因为可用的 FE 选项是三态:[none | modify | access] 其中不存储 'none' BE。

存储如下(mysql):

+-------------+------------------+------+-----+---------+-------+
| Field       | Type             | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| prop_id     | int(10) unsigned | NO   | PRI | NULL    |       |
| modify      | tinyint(1)       | NO   |     | 1       |       |
+-------------+------------------+------+-----+---------+-------+

该模型使用以下 mutator 方法将“修改”转换为 true。

public function setModifyAttribute($value)
{
    $this->attributes['modify'] = ($value === "modify");
}

为 sync() 传递的典型集合如下:

$properties = 
Collection {
  #items: array [
    1 => array [
      "modify" => "modify"
    ]
    7 => array [
      "modify" => "access"
    ]
  ]
}

然后我将按如下方式调用属性的同步:

$this->properties()->sync($properties);

但是,setModifyAttribute() 没有从 sync() 访问。

或者,使用值 'true' 和 'false' sync() 似乎忽略了属性转换提示。

protected $casts = ['modify' => 'boolean'];

我应该对集合运行某种闭包吗?我更喜欢使用以模型为中心的流程。

【问题讨论】:

  • 你找到答案了吗?
  • @danialdezfooli,老实说 - 不。最后我只是解决了这个问题。

标签: php mysql laravel eloquent laravel-eloquent


【解决方案1】:

从 laravel 文档中 setXXXAttribute 方法是这样的

public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }

所以我猜你的代码应该修改:

public function setModifyAttribute($value){
($value==="Modify"):$this->attributes['modify']=1?$this->attributes['modify']=0;

}

也许是错的,祝你好运

【讨论】:

  • 你是对的,我弄错了方法,但是 sync() 无论如何都不会调用属性。
  • 我认为,sync() 方法用于同步提供表中的属性。并且您的模型关系是多对多?
猜你喜欢
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
  • 2016-01-06
  • 2021-11-19
相关资源
最近更新 更多