为什么我的播种机代码中的“关系”不起作用?它可以毫无问题地插入用户模型。但是没有向UserMeta模型插入任何内容。甚至没有任何错误 我在控制器中测试了这段代码。它与“关系”运作良好
<?php
use Illuminate\Database\Seeder;
use App\User;
use App\UserMeta;
class MyUsersTableSeeder extends Seeder
{
/**
* Auto generated seed file.
*
* @return void
*/
public function run()
{
if (User::count() == 0) {
$user = User::create([
'name' => 'Admin',
'email' => 'admin@admin.com',
'password' => bcrypt('password'),
'remember_token' => str_random(60),
]);
$user_meta = new UserMeta([
'meta_key' => 'role',
'meta_value' => 'admin',
]);
$user->UserMeta()->save($user_meta);
}
}
}
模型用户
public function UserMeta()
{
return $this->hasOne('App\UserMeta', 'user_id');
}
模型UserMeta
public function user()
{
return $this->belongsTo('App\User');
}
用户表
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
usermeta表
Schema::create('usermeta', function (Blueprint $table) {
$table->increments('user_meta_id');
$table->integer('user_id')->unsigned();
$table->string('meta_key');
$table->string('meta_value');
});
答案 0 :(得分:1)
请尝试以下代码:
$user_meta = new UserMeta([
'meta_key' => 'role','user_id'=>$user_id,
]);
$user_meta->user_id=$user->id;
$user_meta->save();
答案 1 :(得分:1)
将usermeta
迁移更改为
Schema::create('usermeta', function (Blueprint $table) {
$table->increments('user_meta_id');
$table->integer('user_id')->unsigned();
// add foreign key constraint
$table->foreign('user_id')->references('id')->on('users');
$table->string('meta_key');
$table->string('meta_value');
});
并重新运行迁移。