[英]How to link more than one foreign key in laravel
我正在開發一個銀行應用程序,在我的Laravel模型中,我有一個叫做交易的表。
在該表中,它有一個名為to_id和from_id的列,它是發送貨幣的用戶的id(from_id)和誰接收貨幣的ID(to_id),鏈接到我的User表,
這是CreateTransactionsTable遷移代碼
Schema::create('transactions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('from_id')->unsigned();
$table->foreign('from_id')->references('id')->on('users');
$table->bigInteger('to_id')->unsigned();
$table->foreign('to_id')->references('id')->on('users');
$table->integer('Amount');
$table->enum('TransactionType', ['Credit', 'Debit']);
$table->enum('Status', ['Completed', 'Incomplete']);
$table->timestamps();
});
這是CreateUserTable遷移文件代碼
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('AccountNumber')->unique();
$table->rememberToken();
});
這是交易模型的代碼
class Transactions extends Model{
public function users(){
return $this->belongsTo('App\Users');
}
}
以下是用戶模型的代碼
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'Amount',
];
public function transactions(){
return $this->hasMany('App\Transactions');
}
}
這是我的控制器代碼
public function Transactions(){
$Trans = Transactions::all();
return view('Admin.TranAdmin')->with(['title'=>'Transaction History ', 'Trans'=>$Trans]);
}
這是我的TranAdmin.blade.php代碼
<?php $no = 1; ?>
@foreach ($Trans as $Tran)
<tr>
<td>{{ $no++ }}</td>
<td>{{ $Tran->to_id }}</td>
<td>{{ $Tran->from_id->name }}</td>
<td>{{ $Tran->status }}</td>
<td>{{ $Tran->created_at->format('F jS, Y')}}</td>
<td></td>
</tr>
@endforeach
我現在的問題是,我無法得到發送$Tran->from_id
並收到$Tran->to_id
錢的人的名字
我收到這個錯誤
試圖獲取非對象的屬性(查看:C:\\ xampp \\ htdocs \\ laravel Projects \\ bank \\ iscbank \\ resources \\ views \\ Admin \\ TranAdmin.blade.php)(查看:C:\\ xampp \\ htdocs \\ laravel Projects \\銀行\\ iscbank \\資源\\意見\\管理\\ TranAdmin.blade.php)
我在網上查了但是我看到要做$Tran->User->name
但是因為我有兩列鏈接到users表,我怎么能這樣做
您需要在Transaction模型上定義另外兩個關系。
如下
截至目前,您正在嘗試從模型中的屬性訪問關系的屬性(例如:當您執行此操作時$Trans->from_id
,您只是獲取數據,而不是關系。)而是您需要訪問首先在模型中定義它們然后調用它上面的屬性。
class Transactions extends Model{
public function from(){
return $this->belongsTo('App\Users','from_id', 'id');
}
public function to(){
return $this->belongsTo('App\Users', 'to_id', 'id');
}
//maybe you dont need the user relationship at all
}
然后在模板中,您使用它如下
$transaction->to->name;
$transaction->from->name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.