books
id | title |
---|---|
1 | Example |
orders
id | user_id | amount |
---|---|---|
1 | 1 | 100.00 |
orderables
id | order_id | orderable_id | orderable_type |
---|---|---|---|
1 | 1 | 1 | App\Book |
<?php | |
namespace App; | |
class Album { | |
/** | |
* Get all of the orders for the book. | |
* | |
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany | |
*/ | |
public function orders() | |
{ | |
return $this->morphToMany(Order::class, 'orderable'); | |
} | |
} |
<?php | |
namespace App; | |
class Book { | |
/** | |
* Get all of the orders for the book. | |
* | |
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany | |
*/ | |
public function orders() | |
{ | |
return $this->morphToMany(Order::class, 'orderable'); | |
} | |
} |
<?php | |
namespace App; | |
class Order { | |
/** | |
* Get all of the albums that are assigned this order. | |
* | |
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany | |
*/ | |
public function albums() | |
{ | |
return $this->morphedByMany(Album::class, 'orderable'); | |
} | |
/** | |
* Get all of the books that are assigned this order. | |
* | |
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany | |
*/ | |
public function books() | |
{ | |
return $this->morphedByMany(Book::class, 'orderable'); | |
} | |
} |
<?php | |
Route::get('test', function() { | |
$order = \App\Order::findOrFail(1); | |
return $order->books; | |
}); |