2017-03-17 21 views
0

我有以下表

活動

id 
    name 
    start_date 
    end_date 

EventLineItems(屬於事件&產品)

id 
    event_id 
    product_id 
    quantity 

產品

id 
    name 
    quantity 
    rack 
    section 
    level 
    position 

目前我對events.show銼刀刀片看起來像這樣

@foreach ($event->lineitems as $item) 
    <tr> 
    <td>{{$item->product->id}}</td> 
    <td>{{$item->quantity}}</td> 
    <td>{{$item->product->name}}</a></td> 
    <td>{{$item->resource_id}}</td> 
    <td>{{$item->product->rack}} - {{$item->product->section}} - {{$item->product->level}} - {{$item->product->position}}</td> 
    </tr> 
@endforeach 

我希望能夠調用$用品 - >產品 - >位置在我看來,而不是單獨的每個領域。我認爲這將在我的模型中作爲一個函數,但不知道如何或什麼谷歌。

對於簡單的目的,認爲(發票了LineItem,產品)

+1

你會請你的模型添加到這個職位嗎? –

+0

我做了很多修改 – DevJustin

回答

0

我不知道你的數據庫結構是怎樣的,但我認爲你的項目模型將通過belongsTo產品。所以下面是使用大量猜測工作的例子...

所以你的LineItem模型將包含。

function product() 
{ 
    return $this->belongsTo(Product::class); 
} 

function event() 
{ 
    return $this->belongsTo(Event::class); 
} 

您的活動模式將包含這樣的內容:

function lineItems() 
{ 
    return $this->hasMany(EventLineItem::class); 
} 

然後,當你查詢使用具有雄辯的數據庫,你會做這樣的事情:

$events = Event::with(['lineItems', 'lineItems.product'])->get();

這將讓所有事件,包含所有lineItem和與每個lineItem相關的產品

看到https://laravel.com/docs/5.4/eloquent-relationships#querying-relationshttps://laravel.com/docs/5.4/eloquent-relationships#eager-loading進一步信息基礎上更新的問題

編輯:

您可以在模型中定義的accessorhttps://laravel.com/docs/5.4/eloquent-mutators#accessors-and -mutators

public function getLocationAttribute() 
{ 
    return sprintf('%s - %s - %s - %s', $this->attributes['rack'], $this->attributes['section'], $this->attributes['level'], $this->attributes['position']); 
} 

那麼在你看來,{{ $item->product->location }}

+0

我編輯了我的問題,$ lineitems屬於一個事件和一個產品 – DevJustin

+0

查看更新回答 – Gravy

+0

謝謝,但我已經得到了我所有的項目和我的刀片文件如上所示工作但是我正在尋找DRY鍵入最後​​的方式爲$ item-> product-> location。我知道該列不存在 – DevJustin

相關問題