错误说尝试读取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名称
1条答案
按热度按时间qfe3c7zg1#
您必须定义外键..因为Laravel无法解析外键,Laravel假设您的外键名称为
house_hold_id
更多关于一对一关系的信息
个字符