【问题标题】:Laravel Eloquent relationship returning nullLaravel Eloquent 关系返回 null
【发布时间】:2021-06-20 01:45:08
【问题描述】:

我的 Eloquent 人际关系似乎有问题。我有几个表格要演示

Schema::create('properties', function (Blueprint $table) {
    $table->integer('id')->unsigned()->index();
    $table->integer('propertyid')->unsigned()->index();
    $table->longText('description')->nullable();
    $table->boolean('garden')->nullable();
    $table->boolean('parking')->nullable();
});

Schema::create('address', function (Blueprint $table) {
    $table->integer('propertyid')->unsigned()->index();
    $table->string('name')->nullable();
    $table->string('street')->nullable();

    $table->foreign('propertyid')
        ->references('propertyid')
        ->on('properties')
        ->onDelete('cascade');
});

删除了很多列以减少代码。这些关系非常简单,在 Property.php 中,我使用外键名称定义了要寻址的关系。

public function address()
{
    return $this->hasOne(Address::class, 'propertyid');
}

然后在 Address.php 中我做相反的操作

public function property()
{
    return $this->belongsTo(Property::class, 'propertyid');
}

当我填充我的数据库时,我可以进入地址表,单击 propertyid,它会将我带到正确的属性,所以它似乎设置正确。但是,在我的控制器中,如果我这样做了

$properties = Property::with('address')->paginate(6);

我使用dd输出这个,关系输出返回null

#relations: array:6 [
    "address" => null
]

为什么这不能恢复关系?

谢谢

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您还必须在 hasOne 关系中提及 localkey。根据迁移,看起来两个表列之间的映射是 propertyid 而不是 id

       $table->foreign('propertyid')
            ->references('propertyid')
    

    所以房地产应该是

    public function address()
    {
        return $this->hasOne(Address::class, 'propertyid','propertyid');
    }
    

    还需要你改变belongsTo关系

    public function property()
    {
        return $this->belongsTo(Property::class, 'propertyid', 'propertyid');
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-21
      • 1970-01-01
      • 2014-07-30
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      相关资源
      最近更新 更多