How To Cast Eloquent Pivot Parameters?

前端 未结 5 1872
萌比男神i
萌比男神i 2020-12-14 08:11

I have the following Eloquent Models with relationships:

class Lead extends Model 
{
    public function contacts() 
    {
        return $this->belongsTo         


        
5条回答
  •  情歌与酒
    2020-12-14 08:14

    I had to add some extra checks to have the save and load functions working properly in Laravel 5.

    class BasePivot extends Pivot
    {
        private $loading = false;
    
        public function __construct(Model $parent, array $attributes, $table, $exists)
        {
            $this->loading = true;
            parent::__construct($parent, $attributes, $table, $exists);
            $this->loading = false;
        }
    
        public function setAttribute($key, $value)
        {
            // First we will check for the presence of a mutator for the set operation
            // which simply lets the developers tweak the attribute as it is set on
            // the model, such as "json_encoding" an listing of data for storage.
            if ($this->hasSetMutator($key)) {
                $method = 'set'.Str::studly($key).'Attribute';
    
                return $this->{$method}($value);
            }
    
            // If an attribute is listed as a "date", we'll convert it from a DateTime
            // instance into a form proper for storage on the database tables using
            // the connection grammar's date format. We will auto set the values.
            elseif ($value && (in_array($key, $this->getDates()) || $this->isDateCastable($key))) {
                $value = $this->fromDateTime($value);
            }
    
            /**
             * @bug
             * BUG, double casting
             */
            if (!$this->loading && $this->isJsonCastable($key) && ! is_null($value)) {
                $value = $this->asJson($value);
            }
    
    
            $this->attributes[$key] = $value;
    
            return $this;
        }
    }
    

提交回复
热议问题