Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么不是';我的Laravel一对一关系是否如预期的那样有效?_Php_Laravel_Foreign Keys_Relationship_One To One - Fatal编程技术网

Php 为什么不是';我的Laravel一对一关系是否如预期的那样有效?

Php 为什么不是';我的Laravel一对一关系是否如预期的那样有效?,php,laravel,foreign-keys,relationship,one-to-one,Php,Laravel,Foreign Keys,Relationship,One To One,我有两种型号,交货和装运 交付可以与装运有两种不同的一对一关系:外部装运和内部装运 以下是我如何定义这些关系: class Delivery extends Model { public function outboundShipment() { return $this->hasOne('App\Shipment', 'delivery_id', 'outbound_shipment_id'); } public function inbound

我有两种型号,
交货
装运

交付
可以与
装运
有两种不同的一对一关系:
外部装运
内部装运

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

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
对象并保存它之后,我调用
addRelatedShippings()

在一端,这可以正常工作-如果我调用
$deliveries=Delivery::with('outboundshipping')->with('inboundshipping')->get(),我得到交付列表,每个交付都有
出站装运
入站装运
作为模型上的属性

但是,当我试图在装运时包含交货时,这不起作用。如果我调用
$shippings=shipping::with('delivery')->get(),我获取所有装运,两个字段为空:
delivery\u id
delivery


知道我做错了什么吗?我假设至少,
delivery\u id
字段不应该为空。如前所述,在调用
addRelatedShippings()

之前,我确实在
Delivery
模型上调用
save()
,因为您的装运包含
Delivery\u id
它必须将与交货模型的关系定义为BelongsTo。将您的关系更新为如下所示:

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

}

我想你必须在发货模型上定义两次hasOne关系,就像在交货时一样。嗯,我认为这可能是解决方案,但这不符合我的关系逻辑吗?每批货只有一次交货,我希望它使用相同的字段
Delivery\u id
。这很好,但是您在交货时有两个不同的“键”作为参考装运。It(发货)需要知道使用哪一个。但交付时的两个不同“键”最终是本地键,因此交付模型可以同时具有“出站装运id”和“入站装运id”。。。我真的很困惑。第二个参数应该是外键(根据Laravel docs),这就是为什么我将其设置为“delivery\u id”,以便装运模型使用“delivery\u id”来引用交货。。。还是我遗漏了一些明显的东西?看看装运模型中的交货情况。它有两种链接到传递的方式:入站和出站。当查询它时,装运需要知道在哪里可以找到交货,它是出站的吗?入境?都是?我的错。我最初有这个,得到了同样的结果。我换成了hasOne,尝试了一些不同的东西。