问题描述
我的用户(铅笔)表和角色表之间存在一对一的关系,但是当我在控制器中访问它时,它返回null并且找不到列
Route.php
Route::get('/test','PenggunaController@index');
PenggunaController.php
使用App \ Pengguna;
class PenggunaController extends Controller
{
public function index()
{
$pengguna = Pengguna::find(3);
return response()->json([
'data' => $pengguna
]);
}
}
迁移
create_penggunas_table
public function up()
{
Schema::create('penggunas',function (Blueprint $table) {
$table->id();
$table->string('username');
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
});
}
create_roles_table
public function up()
{
Schema::create('roles',function (Blueprint $table) {
$table->id('id');
$table->string('role_name')->unique();
});
}
型号
Pengguna.php
public function role()
{
return $this->hasOne('App\Role');
}
Role.php
public function pengguna()
{
return $this->belongsTo('App\Pengguna');
}
因此,在PenggunaController.php的方法索引上,我正在获取id = 3的数据。它返回完整数据,出现了role_id,但如果我像$pengguna_role = $pengguna->role->role_name;
一样访问它,则返回错误消息找不到列。然后我尝试更改为$pengguna->roles->role_name;
,它返回错误消息“ not a object”,我尝试了dd($penggunas->roles);
,并且返回null。
SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ roles.pengguna_id”(SQL:从
roles
中选择*,其中roles
。pengguna_id
= 3和roles
。pengguna_id
不能为空限制1)
我可以通过在User::find(3);
然后是Role::where('id',$pengguna->role_id);
的结果中获取role_id来解决此问题。但这让我感到困惑,为什么我不能使用关系直接访问它。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)