Skip to content

Instantly share code, notes, and snippets.

@bobbybouwmann
Last active January 11, 2016 16:24
Show Gist options
  • Save bobbybouwmann/916a047b9a08f1fcfa55 to your computer and use it in GitHub Desktop.
Save bobbybouwmann/916a047b9a08f1fcfa55 to your computer and use it in GitHub Desktop.
Relations for invoices
<?php
namespace App;
class Line extends Model
{
protected $table = 'lines';
protected $fillable = [];
public function details()
{
return $this->belongsTo(App\InvoiceDetail::class, 'invoice_details');
}
}
<?php
namespace App;
class Invoice extends Model
{
protected $table = 'invoices';
// Don't forget to add your fillables
protected $fillable = [];
public function details()
{
return $this->hasMany(App\InvoiceDetail::class, 'invoice_details');
}
}
<?php
namespace App;
class InvoiceDetail extends Model
{
protected $table = 'invoice_details';
protected $fillable = [];
public function invoice()
{
return $this->belongsTo(App\Invoice::class);
}
public function lines()
{
return $this->hasOne(App\Line::class);
}
}
<?php
Schema::create('invoices', function (Blueprint $table)
{
$table->increments('id');
});
Schema::create('invoice_details', function (Blueprint $table)
{
$table->increments('id');
$table->integer('invoice_id')->unsigned();
});
Schema::create('lines', function (Blueprint $table) {
$table->increments('id');
$table->integer('invoice_details_id')->unsigned();
});
$line = Line::create(['name' => 'product1']);
$invoiceDetail = InvoiceDetail::create(['field1' => 'value1']);
$invoiceDetail->line()->save($line);
$line2 = Line::create(['name' => 'product2']);
$invoiceDetail2 = InvoiceDetail::create(['field1' => 'value1']);
$invoiceDetail2->line()->save($line2);
$invoice = Invoice::create(['field1' => 'value1']);
$invoice->details()->saveMany([$invoiceDetail, $invoiceDetail2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment