簡體   English   中英

Laravel - leftJoin和元素的引用

[英]Laravel - leftJoin and reference to elements

我的數據庫中有以下表格:

連接
ID
owner_id

擁有者
ID
名字

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

但它導致“未定義的屬性”。 我應該在foreach循環中添加什么來獲取owners.first_name?

你可以使用Eloquent。 Connection模型中定義關系

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

將兩個表“連接”成一行。 您正在引用->owners對象,它不存在,因為ownersconnections屬性都connections到一行。

這應該工作:

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

但你也應該看到Alexey Mezenin解決方案,這是Laravel慣用的方式,從長遠來看會讓你的生活更輕松。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM