刚从Laravel开始。我已经将我的用户和概要文件模型以及概要文件控制器附加在一起。我的目标是在 profile 表中自动分配外键uID。任何帮助将不胜感激。
用户模型文件
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
// specify which attributes can be filled out during registration
public $timestamps = false;
protected $fillable=['firstname','lastname','email','password',];
public function profile(){
return $this->hasOne(profile::class,'pID','uID');
}
}
配置文件模型文件
namespace App;
use Illuminate\Database\Eloquent\Model;
class profile extends Model
{
//
public $timestamps = false;
protected $fillable = ['summary','uID'];
public function user(){
return $this->belongsTo(user::class,'uID','pID');
}
}
个人资料迁移文件
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
public function up()
{
// create profile table
Schema::create('profiles', function (Blueprint $table) {
$table->increments('pID');
$table->timestamp('created_at')->useCurrent();
$table->string('summary')->default('');
$table->integer('uID')->unsigned();
$table->foreign('uID')->references('uID')->on('users')->onDelete('cascade');
});
}
}
配置文件控制文件
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\profile;
class ProfileController extends Controller
{
public function store(Request $request)
{
// used to store user profile after validation
$this->validate($request,[
'summary' => 'required'
]);
$profile = new profile([
'summary' => $request->get('summary'),
]);
$profile->save();
return redirect()->route('profile.create')->with('success','Profile created');
}
}
答案 0 :(得分:1)
更改您的迁移文件, 正如您以后想要定义关系时一样,因此,您的外部ID字段应该可以为空。
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
public function up()
{
// create profile table
Schema::create('profiles', function (Blueprint $table) {
$table->increments('pID');
$table->timestamp('created_at')->useCurrent();
$table->string('summary')->default('');
$table->integer('uID')->nullable()->unsigned();
$table->foreign('uID')
->references('uID')
->on('users')
->onDelete('cascade');
});
}
}
如果您要在创建配置文件后分配“登录用户”,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\profile;
class ProfileController extends Controller
{
public function store(Request $request)
{
// used to store user profile after validation
$this->validate($request,[
'summary' => 'required'
]);
$profile = new profile([
'summary' => $request->get('summary'),
'uID' => auth()->user()->id,
]);
$profile->save();
return redirect()->route('profile.create')->with('success','Profile created');
}
}
答案 1 :(得分:0)
如果您没有在程序中提供值,则需要在表定义级别提供默认值。
根据您的描述,似乎您在创建用户记录后缺少配置文件。