1

I'm using Laravel & Ardent and having issues saving through the hasMany relationship.

I have two classes.

Workorder:

protected   $table          = 'workorder';
protected   $primaryKey     = 'workorder_id';
public static $relationsData = [
    'dates'         => array(self::HAS_MANY, 'App\WorkOrderDate', 'foreignKey' => 'workorder_id'),
];

WorkOrderDate:

protected   $table          = 'workorder_date';
protected   $primaryKey     = 'date_id';
public static $relationsData = array(
    'workorder'  => array(self::BELONGS_TO, 'App\WorkOrder')
);  

after saving my Workorder (which works fine), I'm trying to save a collection of Date models by executing:

$workorder->dates()->saveMany($myDateCollection->all());

But it's not running the date insert, and it's not giving me any errors. I turned on query logging and it looks like Laravel is trying to run an update instead of an insert. Do I have my relationship defined incorrectly here?

Matt Brunmeier
  • 1,310
  • 2
  • 11
  • 22
  • Im not sure if this is still the case in L5....but back in L3 and 4 I remember that whenever I wanted to save to a relationship, I had to create it first. Only then would pushing an update to the relationship work. It was a wierd bug. I wrote an answer a while ago which goes over the push code, and you can see that it will only save if the relationship already has a corresponding entry. http://stackoverflow.com/questions/17035682/eloquent-push-and-save-difference/17035768#17035768 but again, L5 might be completely different. Just thought Id point that out – Kylie Mar 17 '16 at 23:00
  • That would be super confusing, since the docs note the saveMany method under the heading "Inserting Related Models": https://laravel.com/docs/5.2/eloquent-relationships#inserting-related-models – Matt Brunmeier Mar 17 '16 at 23:03
  • also what is $myDateCollection->all() returning. an array? collection of models? – Kylie Mar 17 '16 at 23:03
  • $myDateCollection is a collection of WorkOrderDate models. Collection->all() returns an array of models. – Matt Brunmeier Mar 17 '16 at 23:05
  • I only see the saveMany() method in the BelongsToMany, or HasOneOrMany classes in L5 relations. Not in the BelongsTo or HasMany. Maybe that has something to do with it?? I dont really know, just pointing it out – Kylie Mar 17 '16 at 23:09
  • HasMany extends HasOneOrMany – Matt Brunmeier Mar 17 '16 at 23:44
  • haha... My brain isnt cooperating today. duuuuuh lol – Kylie Mar 18 '16 at 01:51

1 Answers1

1

I was hydrating my date collection from user input, and when you hydrate a model, Laravel assumes the model exists already. Turns out this is not what I mean to do.

More detail here: https://github.com/laravel/framework/issues/9360

Matt Brunmeier
  • 1,310
  • 2
  • 11
  • 22