为什么我的Laravel一对一关系不按预期工作?

时间:2016-04-14 19:59:47

标签: php laravel foreign-keys relationship one-to-one

我有两个模型,LocaleDelivery

Shipment可以与DeliveriesShipmentOutboundShipment建立两种截然不同的一对一关系。

以下是我如何定义这些关系:

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

1 个答案:

答案 0 :(得分:0)

由于您的货件包含delivery_id,因此必须将交货模型的关系定义为BelongsTo。将您的关系更新为:

class Shipment extends Model
{
    public function delivery() {
        return $this->belongsTo('App\Delivery');
    }   

}