Laravel 设置属性不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44274295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:03:50  来源:igfitidea点击:

Laravel set Attribute not working

phplaraveleloquentlaravel-5.2laravel-eloquent

提问by Peter Hyman

i need 2 function add and update the user socials with serialize array to string before insert to database here my code

我需要 2 个函数添加和更新用户社交与序列化数组到字符串之前插入到数据库这里我的代码

    <?php
use Illuminate\Database\Eloquent\Model as Model;
class User extends Model{
    protected $table = 'user';
    protected $primaryKey = 'user_id';

    protected $fillable = [
        'name', 
        'email', 
        'socials',
    ];

    public function getSocialsAttribute($value){
       return unserialize($value);
    }

    public function setSocialsAttribute($value){
        settype($value, 'array');
        $this->attributes['socials'] = serialize($value);
    }

}

and in my controller

在我的控制器中

$user_id = User::insert($request->post);

the post array with

帖子数组与

array(
   'name'=>'A',
   'email'=>'[email protected]',
   'socials'=> array(
     'facebook' => 'facebook.com',
     'twitter' => 'twiter.com'
   )
)

but the database does not serialize the data !

但是数据库不会序列化数据!

回答by aceraven777

I think it doesn't work on insertmethod. Try to use the createmethod to insert data to database.

我认为它在insert方法上不起作用。尝试使用该create方法将数据插入数据库。

$user = User::create($request->post);

回答by Peter Hyman

No , when i save to database the Socialsis not serialized

不,当我保存到数据库时,Socials它没有被序列化

enter image description here

在此处输入图片说明

This show Array in database , i do like you talk remove getSocialsAttribute

这显示数据库中的数组,我喜欢你说删除 getSocialsAttribute

and does not work .

并且不起作用。