Laravel 给表单模型赋值,来自 join table

Laravel give value to form model, from join table

我有代码来获取数据并像这样连接两个 table:

 $loan = Loan::findOrFail( $id )
            ->join('customers', 'loans.customer_id', '=', 'customers.id')
            ->join('loans_detail','loans.id','=','loans_detail.loans_id')
            ->get();
            return view( 'loans.detail', compact( [ 'loan' ] ) );

然后我 return 将数据发送到:

{!! Form::model( $loan, [ 'method' => 'put' ] ) !!}
{!! Form::text( 'payment_type', null, [ 'class' => 'form-control'] ) !!}

但数据 (payment_type) 没有出现。但是,如果我删除连接代码,则会出现数据 (payment_type)。

如果我将 dd() 用于具有连接 table 的数据库或不使用数据 table

,则会出现一些不同的结果

加入table

Builder {#783 ▼
  #query: Builder {#782 ▶}
  #model: Loan {#779 ▶}
  #eagerLoad: []
  #localMacros: []
  #onDelete: null
  #passthru: array:12 [▶]
  #scopes: []
  #removedScopes: []
}

没有加入 table

Loan {#779 ▼
  #table: "loans"
  #guarded: []
  #connection: "pgsql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:9 [▶]
  #original: array:9 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}

findOrFail() 已经执行查询,之后调用 join() 开始新的查询。

试试这个:

$loan = Loan::whereKey($id)
    ->join('customers', 'loans.customer_id', '=', 'customers.id')
    ->join('loans_detail','loans.id','=','loans_detail.loans_id')
    ->first();

顺便说一句:您应该对这种查询使用关系:
https://laravel.com/docs/5.6/eloquent-relationships