在Laravel Blade中显示表中的相关数据一对一关系

kpbwa7wx  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(82)

错误说尝试读取null上名称。当我尝试

<td>{{ $respondent->household_heads->name }}</td>

字符串
在我的respondent表中,我有一个外键household_id,其中包含respondent所属的household_head。
下面是我的household_heads模式:

Schema::create('household_heads', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

受访者方案:

Schema::create('respondents', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedBigInteger('household_id');
            $table->timestamps();

            $table->foreign('household_id')->references('id')->on('household_heads');
        });

HouseholdHead型号:

class HouseholdHead extends Model
{
    use HasFactory;
    protected $fillable = [];

    public function respondent(){
        return $this->hasOne(Respondent::class);
    }

}

受访者模型

class Respondent extends Model
{
    use HasFactory;

    use HasFactory;
    protected $fillable = [];

    public function household_heads(){
        return $this->belongsTo(HouseholdHead::class);
    }
}

household_head表:


的数据

受访者表:


控制器

public function index()
{
     
    $respondents = Respondent::with('household_heads')->get();
    return view('map', compact('respondents'));

    

}

table.blade.php

@foreach ($respondents as $respondent)
         <tr>
            <td> {{$respondent->name}} </td>
                              
            <td>{{ $respondent->household_heads->name   }}</td>

          </tr>
@endforeach


我想在table.blade.php上显示我的受访者所属的table.blade.php中的household_head名称

qfe3c7zg

qfe3c7zg1#

您必须定义外键..因为Laravel无法解析外键,Laravel假设您的外键名称为house_hold_id
更多关于一对一关系的信息

class HouseholdHead extends Model
{
    use HasFactory;
    protected $fillable = [];

    public function respondent(){
        return $this->hasOne(Respondent::class, 'household_id', 'id');
    }

}

个字符

相关问题