首页 > 解决方案 > 3张表的雄辩关系

问题描述

我想在 user.show 上显示授予特定用户的贷款。

这是贷款金额表 在此处输入图像描述

这是赠款贷款表

在此处输入图像描述

现在在 user.show 我想显示授予该用户的贷款

在我的贷款金额模型上,

public function grantLoans()
{
    return $this->manyToMany('App\LoanAmount','id','amount_id');
}    

在我的 GrantLoanAmount 模型上

public function user() //just update this. this line works
{
    return $this->hasMany('App\User','id','user_id');
}

public function amounts() //just update this. this line works
{
    return $this->hasMany('App\LoanAmount','id','amount_id');
}

在我的用户控制器上

目前我只有这个,

public function show($id)
{
$grantLoan = GrantLoanAmount::where('user_id',$id)->get();
?????
}

我怎么能金额?形成grant_loan_amounts 表?

谢谢你!

标签: laraveleloquent

解决方案


假设您有一个User模型,一个LoanAmount模型和一个GrantLoanAmount模型,并且可以向用户授予多个贷款金额,那么这应该可行

//User model
public function loan_amounts()
{
    return $this->hasManyThrough(
        'App\LoanAmount',
        'App\GrantLoanAmount',
        'user_id',
        'id',
        'id',
        'amount_id'
    );
}

推荐阅读