我认为我对 Laravel 雄辩的关系(版本 7)有误解。主要问题是:它们需要 MySQL 外键才能工作吗?双向都需要 FK 吗?情况:我有用户,我有帐户。每个用户有一个帐户,每个帐户属于一个用户。用户迁移:class CreateUsersTable extends Migration{ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamp('updated_at'); $table->timestamp('email_verified_at')->nullable(); $table->timestamp('created_at')->useCurrent(); }); }}账户迁移:class CreateAccountsTable extends Migration{ public function up() { Schema::create('accounts', function (Blueprint $table) { $table->id('owner'); $table->bigInteger('currency'); $table->integer('currencyGenerators'); $table->foreign('owner')->references('id')->on('users'); $table->timestamp('updated_at'); $table->dateTime('lastResourceUpdate')->nullable()->useCurrent(); $table->timestamp('created_at')->useCurrent(); }); }}因此,我有一个引用 users.id 的 MySQL FKcounts.owner。用户型号:class User extends Authenticatable{ ... public function account(): HasOne { return $this->hasOne(Account::class, 'owner'); }}账户模型:class Account extends Model{ ... public function user(): BelongsTo { return $this->belongsTo(User::class, 'id'); }}我可以检索用户的帐户:$users = User::all();dd($users[0]);App\User {#1030 ▼#primaryKey: "id"...#relations: array:1 [▼"account" => App\Account {#1185 ▶}]...但我无法获取该帐户的用户:$accounts = Account::all();dd($accounts[0]);App\Account {#1241 ▼ #primaryKey: "owner" ... #relations: array:1 [▼ "user" => null ] ...我的用户表中是否需要一个 FK 来引用帐户的所有者?(因为 Laravel 的文档return $this->hasOne('App\Phone', 'foreign_key');在https://laravel.com/docs/7.x/eloquent-relationships#introduction中提到。或者我这里的问题是什么?
- 1 回答
- 0 关注
- 108 浏览
添加回答
举报
0/150
提交
取消