php Laravel 9来自同一个表的两个外键

g6ll5ycj  于 2023-01-19  发布在  PHP
关注(0)|答案(1)|浏览(156)

我有两个表,banks和Transfers。我试图显示一个transfers表,该表显示两个银行帐户之间的资金转移。如果我不使用任何关系,则该表显示相应的id,这意味着它工作正常。问题出现在我想显示相应的银行帐户名称时。我得到一个ErrorException:尝试读取int的属性“accountName”。
enter image description here
有没有人能看一看:
这是我目前拥有的:我的银行模型

class Bank extends Model
{
    use HasFactory;
    protected $fillable = [
        'accountName',
        'bankName',
        'currencyCode',
        'accountNumber',
        'balance',
        'contact',
        'address',
        'created_by',
    ];
}

我的传输模型

class Transfer extends Model
{
    use HasFactory;
    protected $fillable = [
        'fromAccount',
        'toAccount',
        'amount',
        'rate',
        'date',
        'reference',
        'description',
        'created_by',
    ];

    public function fromAccount()
    {
        return $this->belongsTo(Bank::class, 'fromAccount');
    }

    public function toAccount()
    {
        return $this->belongsTo(Bank::class, 'toAccount');
    }
}

我的转接迁移

public function up()
    {
        Schema::create('transfers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('fromAccount');
            $table->unsignedBigInteger('toAccount');
            $table->float('amount', 15, 4);
            $table->double('rate', 15, 8);
            $table->date('date');
            $table->string('reference');
            $table->text('description')->nullable();
            $table->integer('created_by')->default('0');
            $table->timestamps();
            $table->foreign('fromAccount')->references('id')->on('banks');
            $table->foreign('toAccount')->references('id')->on('banks');
        });
    }

我在TransferController中的索引函数

public function index()
    {
        $transfers = Transfer::with('fromAccount', 'toAccount')->get();
        return view('backend.pages.transfers.index', compact('transfers'));
    }

我的视图刀片文件

@foreach ($transfers as $transfer)
 <tr>
   <td class="fw-semibold">{{ $transfer->date }}</td>
   <td>{{ $transfer->fromAccount->accountName }}</td>
   <td>{{ $transfer->toAccount->accountName }}</td>
 </tr>
@endforeach
pgvzfuti

pgvzfuti1#

在我看来,数据保存成功,但加载不正确,可能尝试将参数作为数组传递。
变更

$transfers = Transfer::with('fromAccount', 'toAccount')->get();

$transfers = Transfer::with(['fromAccount', 'toAccount'])->get();

相关问题