【问题标题】:How to relate three tables in laravel如何在laravel中关联三个表
【发布时间】:2021-06-25 15:14:58
【问题描述】:

我正在尝试在 laravel 中开发一个 p2p 应用程序。

我的数据库中有三个表,即用户、贷款和分期付款。

现在,用户和贷款可以有多个分期付款,每个分期将属于一个用户和一个贷款。

那么我该如何定义这种关系呢?我需要多态关系吗?如果是这样,如何将用户和贷款与单个分期付款联系起来?

【问题讨论】:

    标签: laravel eloquent laravel-8 eloquent-relationship


    【解决方案1】:

    每一期将属于一个用户一笔贷款。

    这几乎回答了这个问题。

    如果您的要求是“每个分期付款将属于要么用户贷款”,那么关系将是多态的。

    最小的表结构

    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        ... // other users fields or indexes.
    });
    
    Schema::create('loans', function (Blueprint $table) {
        $table->bigIncrements('id');
        ... // other loans fields or indexes.
    });
    
    Schema::create('installments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->foreignId('user_id')->constrained('users');
        $table->foreignId('loan_id')->constrained('loans');
        ... // other installments fields or indexes.
    });
    

    如果分期付款的user_idloan_id 可以为空,请在->constrained() 之前添加->nullable()。例如:

    Schema::create('installments', function (Blueprint $table) {
        ...
        $table->foreignId('user_id')->nullable()->constrained('users');
        ...
    });
    

    如果您不能将多个分期付款与同一用户/贷款对关联,请添加唯一索引。

    Schema::create('installments', function (Blueprint $table) {
        ...
        $table->unique(['user_id', 'loan_id']);
        ...
    });
    

    要定义的关系

    用户模型:

    • public function installments() { return $this->hasMany(Installment::class); }
    • public function loans() { return $this->belongsToMany(Loan::class, 'installments'); }

    贷款模式:

    • public function installments() { return $this->hasMany(Installment::class); }
    • public function users() { return $this->belongsToMany(User::class, 'installments'); }

    分期付款模式:

    • public function loan() { return $this->belongsTo(Loan::class); }
    • public function user() { return $this->belongsTo(User::class); }

    https://laravel.com/docs/eloquent-relationships#inserting-and-updating-related-models

    https://laravel.com/docs/eloquent-relationships#syncing-associations

    https://laravel.com/docs/eloquent-relationships#updating-a-record-on-the-intermediate-table

    syncWithoutDetaching()updateExistingPivot() 如果您有唯一约束,则特别重要。

    【讨论】:

    • 就像添加列一样。
    • 不,如何进行 CRUD 操作?
    • 具有 hasMany 或 belongsToMany 关系。
    猜你喜欢
    • 2020-06-23
    • 2014-02-14
    • 2017-02-15
    • 1970-01-01
    • 2020-07-16
    • 2019-07-13
    • 2021-01-27
    • 2012-04-04
    • 2017-03-10
    相关资源
    最近更新 更多