php - 如何在laravel中链接多个外键
问题描述
我正在开发一个银行应用程序,在我的 Laravel 模型中,我有一个名为 transactions 的表。
在该表中,它有一个名为 to_id 和 from_id 的列,这是发送资金的用户的 ID(from_id)和接收资金的用户的 ID(to_id),它链接到我的用户表,
这是 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\resources\views\Admin\TranAdmin.blade.php)
我在网上查了一下,但我看到是要做的,$Tran->User->name
但是因为我有两列链接到用户表,我该怎么做
解决方案
您将需要在 Transaction 模型上再定义 2 个关系。
像下面
到目前为止,您正在尝试从模型的属性中访问关系的属性(例如:当您这样做时$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;
推荐阅读
- reactjs - 在功能组件中调用 API
- sql - 寻找相同的交易者在 3 分钟内购买和出售相同的产品
- ios - DispatchQueue.main.async 导致搜索挂起。迅速
- google-bigquery - 如何知道 bigquery 表中的最小集群大小?
- r - 多个图形命令在 R 图中不起作用?
- python - python kivy 背景颜色变白
- flutter - 颤振改变底部导航栏高度
- suse - 如何在 SLES 12 上安装 podman
- r - 使用 ggplot2 基于两个因子变量(在 x 轴上)对箱线图进行排序
- nestjs - 如何使用 nginx 在数字海洋中运行nestjs?