Laravel:数据透视表指向多个表

时间:2016-05-25 12:45:17

标签: pivot laravel-5.2

假设我有一个orders表,它与其他三个名为typingstranslatestheses的表有多对多的关系。我知道数据透视表应该在某种程度上像many to many polymorphic relation,但这并不是我想要的。 我应该如何实施数据透视表?

1 个答案:

答案 0 :(得分:1)

您将通过名为orderables

的数据透视表创建与订单和其他三个表的多态关系
// 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;