【发布时间】:2019-01-30 11:08:59
【问题描述】:
我正在使用 laravel 5.5 构建一个多重身份验证系统。我有 Admin 和 AdminRole 模型以及它们各自的迁移。Admin 和 AdminRole 模型之间存在一对一的关系。一切正常。但是当我尝试像这样访问 admin_role 时:
$admin->adminRole->name;它会抛出这样的错误:
使用消息'SQLSTATE [42S22] 照亮/数据库/查询异常:找不到列:1054 'where 子句'中的未知列'admin_roles.admin_id'(SQL:select * from
admin_roleswhereadmin_roles.admin_id= 1 和admin_roles.admin_id不是空限制 1)'。
我已经尝试了很多小时,但无法弄清楚问题所在。任何帮助将不胜感激。提前致谢。
Admin.php 模型:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'ip_address',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function adminRole() {
return $this->belongsTo('App\Models\AdminRole');
}
}
admins.php 迁移
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->integer('admin_role_id')->unsigned()->nullable();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->ipAddress('ip_address')->nullable();
$table->string('photo')->default('avatar.png');
$table->boolean('status')->default(true);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
AdminRole.php 模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AdminRole extends Model
{
//
protected $fillable = ['name'];
public function admin()
{
return $this->hasOne('App\Models\Admin');
}
}
admin_role.php 迁移
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdminRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('admin_roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admin_roles');
}
}
【问题讨论】:
-
很奇怪。您的关系定义是正确的。如果您明确指定外键,有什么变化吗?
return $this->belongsTo('App\Models\AdminRole', 'admin_role_id'); -
我也试过指定外键;但问题依旧
-
我已经复制了您的设置here。它正在工作。我们可以看到您在进行关系调用的控制器/刀片吗?
-
我在 tinker 上测试
标签: php laravel-5.5