Laravel : pivot table 指向多个 tables

Laravel : pivot table point to multiple tables

假设我有一个 orders table 将与另外三个名为 typingstranslatestheses 。我知道 pivot table 应该有点像 many to many polymorphic relation 但这并不是我想要的。 我应该如何实施 pivot table?

您将通过名为 orderables

的枢轴 table 创建与订单和其他三个 table 的多态关系
// TABLES NEEDED
orders
  id - integer

typings
  id - integer

translates
  id - integer

theses
  id - integer

orderables
  order_id - integer
  orderable_id - integer
  orderable_type - string


// MODELS/RELATIONSHIPS NEEDED
class Typing extends Model
{
    public function orders()
    {
        return $this->morphToMany('App\Order', 'orderable');
    }
}
class Translate extends Model
{
    public function orders()
    {
        return $this->morphToMany('App\Order', 'orderable');
    }
}
class Thesis extends Model
{
    public function orders()
    {
        return $this->morphToMany('App\Order', 'orderable');
    }
}
class Order extends Model
{
    public function typings()
    {
        return $this->morphedByMany('App\Typing', 'orderable');
    }
    public function translates()
    {
        return $this->morphedByMany('App\Translate', 'orderable');
    }
    public function theses()
    {
        return $this->morphedByMany('App\Thesis', 'orderable');
    }
}

那么,你可以得到这样一个模型的订单:

$thesis = Thesis::find(1);
$orders = $thesis->orders;

反之:

$order = Order::find(1);
$theses = $order->theses;