为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel 的雄辩关系和 MySQL 的外键——belongsTo 不会产生关系

Laravel 的雄辩关系和 MySQL 的外键——belongsTo 不会产生关系

PHP
喵喔喔 2023-11-03 15:14:53
我认为我对 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 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

您必须在帐户模型中使用“所有者”列

return $this->belongsTo(User::class, 'owner','id');


查看完整回答
反对 回复 2023-11-03
  • 1 回答
  • 0 关注
  • 52 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信