假设我有一个orders
表,它与其他三个名为typings
,translates
和theses
的表有多对多的关系。我知道数据透视表应该在某种程度上像many to many polymorphic relation,但这并不是我想要的。
我应该如何实施数据透视表?
答案 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;