2017-03-17 22 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

相关问题