【发布时间】:2019-05-08 22:34:22
【问题描述】:
我有一个用户表:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->integer('role_id')->unsigned();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
角色表:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('role');
$table->timestamps();
});
还有一张付款表:
Schema::create('payments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('driver_id')->unsigned();
$table->integer('amount');
$table->date('payment_date');
$table->timestamps();
});
我还对角色 (role_id) 上的用户添加了外部约束。
Schema::table('users', function ($table) {
$table
->foreign('role_id')
->references('id')
->on('roles')
->onUpdate('cascade');
});
当我尝试使用faker 生成虚拟付款时,我试图从users 中获取随机user_id,其中role 是user,另一个随机user_id 来自users,其中@987654331 @ 是driver。
$factory->define(App\Models\Payment::class, function (Faker $faker) {
return [
'user_id' => App\User:: //get user
whereHas('roles', function ($query) {
$query->where('role', 'user');}) //where its role is user
->select('id') //get its id
->get()
->random(),
'driver_id' => App\User::
whereHas('roles', function ($query) {
$query->where('role', 'driver');})
->select('id')
->get()
->random(),
'amount' => $faker->randomNumber,
'payment_date' => $faker->date($format = 'Y-m-d', $max = 'now')
];
});
但是 whereHas 会抛出错误:
Illuminate\Database\QueryException : SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select `id` from `users` where exists (select * from `roles` where `users`.`id` = `roles`.`user_id` and `role` = driver))
如果我像这样删除whereHas 部分,它会起作用:
App\User::select('id')
->get()
->random(),
我确定在 whereHas 查询中我没有在 roles 表中查找 user_id,那么它为什么要这样做呢?
编辑:这是我的模型
角色
class Role extends Model
{
protected $table = 'roles';
protected $fillable = [
'role'
];
public function user()
{
return $this->hasMany('App\User');
}
}
用户
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function payments()
{
return $this->hasMany('App\Models\Payment');
}
public function roles()
{
return $this->belongsTo('App\Models\Role');
}
}
【问题讨论】:
-
你也可以发布你的模型类吗?
-
你试过
php artisan config:cache吗?在命令行中?