jeudi 22 juillet 2021

Save model outside of for-each loop

Assuming the model Order

class Order extends Model
{
    use HasFactory;

    protected $table = 'order';

    protected $primaryKey   = 'id';
    public $incrementing = false;
    protected $keyType = 'string';
    protected $guarded = [];

    public function extra(){
        return $this->hasOne(Extra::class);
    }

    public function products(){
        return $this->hasMany(Product::class);
    }
}

and the Model Extra

class Extra extends Model
{

    use HasFactory;
    protected $table = 'extra';
    protected $guarded = [];

    public function order(){
        $this->belongsTo(Order::class);
    }

}

and the Model product

class Product extends Model
{
    use HasFactory;
    protected $table = 'product';
    protected $guarded = [];
    public function order(){
        return $this->belongsTo(Order::class);
    }
}

Now, from an API i receive data. With these data i want to feed the models and then store the info to DB.

The approach there is atm is

foreach ($list as $item) {

    $order = new Order();
    $order->id = $item['id'];
    $order->title = $item['title'];
    $order->save();

    $extra = new Extra();
    $extra->foo= $item['path']['to']['foo'];
    $extra->bar= $item['path']['to']['bar'];
    $order->extra()->save($extra)
    
    $order->products()->createMany($item['path']['to']['products']);
}

The problem is that this code saves three times for each loop, one for order, one for extra, one for product. I would like to know if there is another way that i can use in order to gather the data inside the for-each and outside of it, to make something like Order::insert($array_of_data);



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3hXLIz5
via IFTTT

Aucun commentaire:

Enregistrer un commentaire