【问题标题】:Laravel 5.2: Mutators - How to combine two columns into one with mutatorsLaravel 5.2: Mutators - 如何使用 mutators 将两列合并为一列
【发布时间】:2016-08-26 11:45:45
【问题描述】:

我的数据库中有一个contact 列。在表单上,​​我还显示国家代码,然后用户输入他的联系电话。

在 DB 中我有单列,我想设置一个 mutator,以便我可以连接 countryCode-ContactNumber 并保存到 DB。

我在用户模型中写的是:

public function setContactAttribute($value)
{
    // $this->attributes['contact'] = $this->attributes['country'].'-'.$value;
    $this->attributes['contact'] = $this->country.'-'.$value;
}

这不工作! 我们可以在 L5.2 Mutators 中添加两个以上的字段吗? 非常感谢。

【问题讨论】:

  • 如何用数据填充模型?
  • 对不起!!我不明白你想说什么@Skysplit。我在用户模型上使用 Create 方法。
  • 你是使用Model::fill()还是其他方式?
  • 我在用户模式下使用 Create 方法。喜欢User::Create($request->all());
  • 当contact 字段发生突变时,模型数据中可能不存在country 字段。创建模型后,您的 contact 字段是否看起来像 -{contactValue}?

标签: php laravel-5.2 mutators


【解决方案1】:

在你的 mutator 函数中使用 Request

public function setContactAttribute($value) { $this->attributes['contact'] = Request::input('country').'-'.$value; }

希望这对某人有所帮助。

【讨论】:

  • 这使用请求中的国家/地区值,问题是是否可以使用在此实例上设置的另一个字段中的值。
  • 是的 可能的。您必须使用“$this”访问该值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
相关资源
最近更新 更多