You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中使用驼峰式(camelCase)foreignId建立关联?

Laravel中使用驼峰式外键关联模型的解决方案

1. 修正数据库迁移的外键定义

你的AdminUser迁移里的外键定义不完整,需要先创建匹配类型的字段,再设置关联约束:

Schema::create('AdminUser', function (Blueprint $table) {
    $table->id();
    // 创建与User表id类型匹配的userId字段
    $table->unsignedBigInteger('userId');
    // 完整定义外键关联规则
    $table->foreign('userId')->references('id')->on('User');
    $table->integer('pin');
    $table->string('passcode');
    $table->timestamp('updatedAt');
    $table->timestamp('createdAt');
});

2. 在AdminUser模型中手动指定关联外键

Laravel默认使用蛇形命名(如user_id)匹配外键,所以用驼峰式userId时,必须在关联方法里显式指定参数:

// app/Models/AdminUser.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class AdminUser extends Model
{
    // 指定表名(Laravel默认查找蛇形命名表)
    protected $table = 'AdminUser';
    // 指定驼峰式时间字段
    const CREATED_AT = 'createdAt';
    const UPDATED_AT = 'updatedAt';

    // 关联User模型
    public function user()
    {
        // 参数依次为:关联模型、当前表的外键、关联表的主键
        return $this->belongsTo(User::class, 'userId', 'id');
    }
}

3. (可选)配置User模型的反向关联

如果需要从User模型关联到AdminUser,同样要手动指定外键:

// app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\AdminUser;

class User extends Model
{
    protected $table = 'User';
    const CREATED_AT = 'createdAt';
    const UPDATED_AT = 'updatedAt';

    public function adminUser()
    {
        // 指定关联表的外键字段
        return $this->hasOne(AdminUser::class, 'userId');
    }
}

完成以上配置后,即可正常通过$adminUser->user获取关联的User数据。

内容的提问来源于stack exchange,提问作者Mark78L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 16:33:10