gpt4 book ai didi

php - Laravel - leftJoin 和对元素的引用

转载 作者:行者123 更新时间:2023-11-29 05:06:00 25 4
gpt4 key购买 nike

我的数据库中有以下表格:

连接
编号
owner_id

所有者
编号

ConnectionsController.php

$connections = DB::table('connections')
->leftJoin('owners', 'owners.id', '=', 'connections.owner_id')
->get();

return view('connections.index', ['connections' => $connections]);

如何在 forearch 循环中引用 owners.first_name?我的 connections/index.blade.php

中有这样的内容
@foreach($connections as $element)
{{ $element->owners->first_name }}
@endforeach

但它会导致“未定义的属性”。我应该在我的 foreach 循环中放入什么来获取 owners.first_name?

最佳答案

您可以使用 Eloquent。定义一个 relationshipConnection 模型中:

public function owner()
{
return $this->belongsTo(Owner::class);
}

加载与所有者的连接:

$connections = Connection::with('owner')->get();

显示数据:

@foreach($connections as $element)
{{ $element->owner->first_name }}
@endforeach

如果不是所有连接都有所有者,请执行以下操作:

@foreach($connections as $element)
{{ optional($element->owner)->first_name }}
@endforeach

或者:

@foreach($connections as $element)
{{ $element->owner ? $element->owner->first_name : 'There is no owner' }}
@endforeach

关于php - Laravel - leftJoin 和对元素的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48085050/

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