How To Cast Eloquent Pivot Parameters?

前端 未结 5 1856
萌比男神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:24

    Since this is an attribute on the pivot table, using the $casts attribute won't work on either the Lead or Contact model.

    One thing you can try, however, is to use a custom Pivot model with the $casts attribute defined. Documentation on custom pivot models is here. Basically, you create a new Pivot model with your customizations, and then update the Lead and the Contact models to use this custom Pivot model instead of the base one.

    First, create your custom Pivot model which extends the base Pivot model:

     'boolean'];
    }
    

    Now, override the newPivot() method on the Lead and the Contact models:

    class Lead extends Model {
        public function newPivot(Model $parent, array $attributes, $table, $exists) {
            return new \App\PrimaryPivot($parent, $attributes, $table, $exists);
        }
    }
    
    class Contact extends Model {
        public function newPivot(Model $parent, array $attributes, $table, $exists) {
            return new \App\PrimaryPivot($parent, $attributes, $table, $exists);
        }
    }
    

提交回复
热议问题