我有两个模型,Locale
和Delivery
。
Shipment
可以与Deliveries
:Shipment
和OutboundShipment
建立两种截然不同的一对一关系。
以下是我如何定义这些关系:
InboundShipment
创建class Delivery extends Model
{
public function outboundShipment() {
return $this->hasOne('App\Shipment', 'delivery_id', 'outbound_shipment_id');
}
public function inboundShipment() {
return $this->hasOne('App\Shipment', 'delivery_id', 'inbound_shipment_id');
}
public function addRelatedShipments() {
$newOutboundShipment = new Shipment();
$newOutboundShipment->status = 'Delivery Outbound';
$newOutboundShipment->save();
$this->outboundShipment()->save($newOutboundShipment);
$newInboundShipment = new Shipment();
$newInboundShipment->status = 'Inbound';
$newInboundShipment->save();
$this->inboundShipment()->save($newInboundShipment);
}
}
class Shipment extends Model
{
public function delivery() {
return $this->hasOne('App\Delivery');
}
}
对象并保存后,我致电Delivery
。
一方面,这很好用 - 如果我致电addRelatedShipments()
,我会收到送货清单,每件送货都有$deliveries = Delivery::with('outboundShipment')->with('inboundShipment')->get();
和outbound_shipment
作为模型的属性。
但是,当我尝试将货件包含在货件中时,这不起作用。如果我拨打inbound_shipment
,我会收到所有货件,两个字段为空:$shipments = Shipment::with('delivery')->get();
和delivery_id
。
知道我在这里做错了吗?我假设至少,delivery
字段不应该为空。如上所述,我在致电delivery_id
之前会在save()
模型上致电Delivery
。
答案 0 :(得分:0)
由于您的货件包含delivery_id
,因此必须将交货模型的关系定义为BelongsTo。将您的关系更新为:
class Shipment extends Model
{
public function delivery() {
return $this->belongsTo('App\Delivery');
}
}