与Laravel Eloquent有很多很多关系

时间:2014-08-05 08:04:42

标签: laravel many-to-many eloquent

简而言之,我确实有联系人和公司的名单。 一家公司有多个联系人,但我也希望跟踪联系人所服务的公司。

我有一个数据透视表来创建多对多关系,还有一个额外的列'contractstatus',这样我就可以看到该联系人是否仍在为该公司工作。

我想要的是一张包含所有联系人的表格。 在一个领域,我想打印出联系人仍在工作的所有公司。 通过弹出按钮,我想查看整个工作历史。

在联系模式中我有:

public function organizations()
{
    return $this->belongsToMany('Organization');
}

在控制器中我有:

public function index()
{
    //get all contacts
    $contacts = Contact::all();

    //load the view and pass the results
    return View::make('contact.index')
                 ->with('contacts', $contacts);
}

如何在我的观点中打印出contractstatus处于活动状态的公司?

我是否需要将弹出数据作为新视图文件处理?

1 个答案:

答案 0 :(得分:0)

首先,您需要在查询中获取数据透视数据,并且可能需要加载性能......

public function index()
{
    //get all contacts
    $contacts = Contact::with('organizations')->withPivot('contractstatus')->get();

    //load the view and pass the results
    return View::make('contact.index')
                 ->with('contacts', $contacts);
}

然后,您只需遍历视图中的数据。您可能希望通过将其放在表格或类似的东西中来更好地格式化。希望你明白了。我刚刚添加了类来获​​取jQuery的内容。

@foreach($contacts as $contact)
    <span class='contact' style="cursor: pointer;">{{{ $contact->name }}}</span>
    <div class='active-organizations'>
        @foreach($contact->organizations as $organization)
            @if($organization->pivot->contractstatus == 'A')
                {{{ $organization->name }}}
            @endif
        @endforeach
    </div>
    <div class='all-organizations' style="display: none;">
        @foreach($contact->organizations as $organization)
            {{{ $organization->name }}}
        @endforeach
    </div>
@endforeach

就显示所有组织的新文件而言,这完全取决于您。我刚刚将所有组织插入到隐藏的div中,以便我们可以在用户单击联系人时显示/隐藏该组织。使用jQuery非常容易。

$(document).ready(function() {
    $('.contact').on('click', function() {
        if($(this).next('.active-organizations').is(':visible')) {
            $(this).next('.active-organizations').hide()
            $(this).next('.all-organizations').show()
        } else {
            $(this).next('.active-organizations').show()
            $(this).next('.all-organizations').hide()
        }
    });
});
相关问题