【问题标题】:eloquent relation shows null雄辩的关系显示为空
【发布时间】:2020-11-19 07:51:49
【问题描述】:

我有这样的用户和项目迁移:

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('last_used_society_id');
            $table->bigInteger('last_used_project_id');
            $table->rememberToken();
            $table->timestamps();
        });

Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('eplan_name')->nullable();
            $table->bigInteger('society_id');
            $table->timestamps();

            //$table->foreign('user_id')->references('id')->on('users');
        });

        Schema::table('projects', function (Blueprint $table) {
            $table->foreign('society_id')->references('id')->on('societies');
        });

添加外星人后修改表用户:

    Schema::table('users', function (Blueprint $table) {
        $table->foreign('last_used_society_id')->references('id')->on('societies');
        $table->foreign('last_used_project_id')->references('id')->on('projects');
    });

在用户模型中我有这个:

public function ActualProject(){
    return $this->belongsTo('App\Models\Project', 'users_last_used_project_id_foreign');
}

public function ActualSociety(){
    return $this->belongsTo('App\Models\Society', 'users_last_used_society_id_foreign');
}

但是当我尝试调用$user->ActualProject 时,它会返回null

【问题讨论】:

    标签: laravel eloquent foreign-keys


    【解决方案1】:

    为什么要使用“users_last_used_project_id_foreign”?

    直接使用列名...

    public function ActualProject(){
        return $this->belongsTo('App\Models\Project', 'last_used_project_id');
    }
    

    【讨论】:

    • 不错。谢谢你不知道我可以使用列名...我在网上找到的是使用外键
    • @Petr,如果你的外国身份证是project_id,那么你不需要在你的关系中定义它。 Laravel 会抓住它。你修改了,所以你需要告诉 laravel 你的主键名。
    猜你喜欢
    • 2013-04-10
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2014-08-27
    相关资源
    最近更新 更多