gpt4 book ai didi

php - 如何在 Laravel 中链接多个外键

转载 作者:可可西里 更新时间:2023-11-01 13:22:09 24 4
gpt4 key购买 nike

我正在开发一个银行应用程序,在我的 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');
}
}

这是我的 Controller 代码

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 钱的人的姓名

我收到这个错误

Trying to get property of non-object (View: C:\xampp\htdocs\laravel Projects\bank\iscbank\resources\views\Admin\TranAdmin.blade.php) (View: C:\xampp\htdocs\laravel Projects\bank\iscbank\resources\views\Admin\TranAdmin.blade.php)

我在网上查了一下,但我看到是要执行 $Tran->User->name 但是因为我有两列链接到用户表,我该怎么做

最佳答案

您需要在事务模型上再定义 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;

关于php - 如何在 Laravel 中链接多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com