控制器在laravel中两个表之间的一对一关系



我有一个表用户表,希望将地址表与用户表主键连接起来,用户表主键是地址表中的外键。

请让我知道如何通过Laravel中的控制器在这两个表之间执行一对一关系,并在视图中显示它们。

您只需在Model文件中添加一个雄辩的关系即可实现这一点。

用户.php

<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class User extends Model
{
/**
* Get the phone associated with the user.
*/
public function address()
{
return $this->hasOne(Address::class);
}
}

地址.php

<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Address extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}

注意:以上两个模型都默认将user_id作为Address表中的外键。

要在控制器、中访问此关系

$address = User::find($user_id)->address;

要在View中访问此关系,

{{ $user->address->pincode }}

由于这是一篇重复的帖子,您可以参考在视图中显示Laravel关系中的一对一关系

最新更新