繁体   English   中英

laravel关系返回null

[英]laravel relation returning null

以下内容一直困扰着我。

更新

首先,我发布了一个不打算发布的代码。 我更新了代码。 请看一下。

一个叫盘子的桌子

 $table->increments('id');
 $table->integer('equipment_status_code_id')->unsigned();
 $table->foreign('equipment_status_code_id')->references('id')->on('equipment_status_codes')->onDelete('cascade')->onUpdate('cascade');

和模型

public function equipmentStatusCode()
{
   return $this->belongsTo('App\Models\EquipmentStatusCode');
}

设备状态代码

   public function plate()
    {
         return $this->hasOne('App\Models\Plate');
    }

在路线上我这样做

   $data = Plate::find(1);
   $att = $data->equipmentStatusCode;

   dd($att);

并且工作正常。

但是相反,它将无法正常工作并返回null

$data = EquipmentStatusCode::find(1);
$att = $data->plate;

dd($att);

有人告诉我怎么回事?

具有BelongsTo关系的模型的表中应具有外键 反之亦然。 因此,只需交换关系即可。

平板型号:

public function equipmentStatusCode()
{
   return $this->hasOne('App\Models\EquipmentStatusCode');
}

设备状态代码模型:

public function plate()
{
   return $this->belongsTo('App\Models\Plate');
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM