laraveleloquentmass-assignment

Laravel Eloquent firstOrCreate doesn't work properly


I'm used to it but today this problem makes me weak..;;

class Market {
    // ..
    public function ttl()
    {
        return $this->ttlRelation()->firstOrCreate(
            ['market_id' => $this->id],
            ['tier' => 0, 'direction'=>0]
        );
    }
}

The Market model has one TTL model. I know that firstOrCreate method finds an item as first given array and if it doesn't exists create a new one as persist, returns it.

Besides, its mass-assignment so I filled up $fillable property on ttl model..

class TradingTacticalLayer extends Model
{
    public $timestamps = false;
    protected $fillable = ['direction', 'tier'];
}

..and I'm getting SQLSTATE[HY000]: General error: 1364 Field 'direction' doesn't have a default value (SQL: insert into "trading_tactical_layer_test" ("tier", "market_id") values (0, 1)) message. I cannot understand why this method won't filled up insert field list proper way. I expect, if I edit $fillable property as ['direction'], SQL would implode ("direction") as insert field and it doesn't.

In general, from my experience, I just set those fields as nullable or manually set a default value. At this time, I want to know why this weird happens and what am I doing wrong.


Solution

  • Well, probably, optimize:clear solve the problem.

    I still don't know what makes this error but if you experience mismatch between $fillable property and inserting field list, optimize:clear is an option anyway..