mardi 21 mai 2019

Laravel 5 - calling create() on hasMany relationship with conditions

I have a couple of models - let's call them Item and Ean. In Item model there are a couple of hasMany relations to the Ean model.

  public function eans() {
    return $this->hasMany(Ean::class)->orderBy('type', 'asc')->orderBy('id', 'asc');
  }

  public function eans_type_1() {
    return $this->hasMany(Ean::class)->where('type', 1)->orderBy('id', 'asc');
  }

  public function eans_type_2() {
    return $this->hasMany(Ean::class)->where('type', 2)->orderBy('id', 'asc');
  }

When I want to associate a new Ean model to the Item, I'm using create() :

$item->eans()->create(['ean' => $value, 'type' => 1]);
or
$item->eans()->create(['ean' => $value, 'type' => 2]);

Is there a way to define hasMany relation in a way that I'll be able to do this :

$item->eans_type_1()->create(['ean' => $value]);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire