Laravel - leftJoin和元素的引用

时间:2018-01-03 20:59:36

标签: php mysql laravel left-join

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

连接
id
owner_id

所有者
id
first_name

ConnectionsController.php

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

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

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

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

但它导致“Undefined property”。我应该在foreach循环中添加什么来获取owners.first_name?

2 个答案:

答案 0 :(得分:2)

你可以使用Eloquent。在Connection模型中定义relationship

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

答案 1 :(得分:1)

加入"加入"两个表都成一行。您引用的->owners对象并不存在,因为ownersconnections的属性都会合并为一行。

这应该有效:

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

但你也应该看到Alexey Mezenin解决方案,这是Laravel惯用的方式,从长远来看会让你的生活更轻松。