Laravel Eloquent Relationships
While incomplete currently, the hope is to make this more consolidated than the Laravel docs
One to One
erDiagram
Product {
int id
}
Description {
int product_id
string short
}
Product ||--|| Description : description
Models
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
public function description()
{
return $this->hasOne(Description::class);
}
}
class Description extends Model {
public function product()
{
return $this->belongsTo(Product::class);
}
}
Create Product Description
$product->description()->create(['short' => 'Lorem ipsum dolor sit amet.']);
// or
$description = new Desciption(['short' => 'Lorem ipsum dolor sit amet.']);
$product->description()->save($description);
Get Short Description From Product
$product->description->short;
// or
$product->description()->first()->short;
One to Many
erDiagram
User {
int id
string name
}
Order {
int user_id
string note
}
User ||--o{ Order : orders
Models
use Illuminate\Database\Eloquent\Model;
class User extends Model {
public function orders()
{
return $this->hasMany(Settings::class);
}
}
class Order extends Model {
public function user()
{
return $this->belongsTo(User::class);
}
}
Create Order
$user->orders()->create(['note' => 'foo']);
// or
$order = new Order(['note' => 'foo']);
$user->orders()->save($order);
Get Order Attribute From User Model
$user->orders()->whereKey(1)->first()->note;
Get User Attribute From Order Model
$order->user->name;
// or
$order->user()->first()->name;
Many to Many
erDiagram
Category {
int id
string name
}
Product {
int id
}
ProductCategory {
int product_id
int category_id
}
Product ||--o{ ProductCategory : categories
Category ||--o{ ProductCategory : products
Models
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
public function categories()
{
return $this->belongsToMany(Cateogry::class);
}
}
class Category extends Model {
public function products()
{
return $this->belongsToMany(Product::class);
}
}
Polymorphic One to Many
erDiagram
Order {
int attribution_id
string attribution_type
}
Referral {
int id
string code
}
Campaign {
int id
string code
}
Referral ||--o{ Order : attributions
Campaign ||--o{ Order : attributions
Models
use Illuminate\Database\Eloquent\Model;
class Order extends Model {
public function attribution()
{
return $this->morphTo();
}
}
class Referral extends Model {
public function attributions()
{
return $this->morphMany(Order::class, 'attribution');
}
}
class Campaign extends Model {
public function attributions()
{
return $this->morphMany(Order::class, 'attribution');
}
}
Associate Referral with Order
$order->attribution()->associate($referral);
$order->save();
Get Attribution Attribute From Order
$order->attribution->code;
// or
$order->attribution()->first()->code;