检查关系laravel和打印结果

时间:2018-06-07 08:04:46

标签: php laravel

我有关系,在foreach中我检查是否存在这种关系然后打印结果,但是如果是,则打印结果没有关系。

@foreach($attr as $at)
@if($at->related)
    <option value="{{ $at->related->id }}">
            @if($at->value)
                {{ $at->related->value }}
            @else
                {{ $at->related->extra['first_name'] ? 'First Name and Lastname: ' . $at->related->extra['first_name'] : '' }} {{ $at->related->extra['last_name'] }} |
                {{ $at->related->extra['email'] ? 'Email: ' . $at->related->extra['email'] : '' }} |
                {{ $at->related->extra['telephone'] ? 'Tel: ' . $at->related->extra['telephone'] : '' }}
            @endif
    </option>
@else
    <option value="{{ $at->id }}">
        @if($at->value)
            {{ $at->value }}
        @else
            {{ $at->extra['first_name'] ? 'First Name and Lastname: ' . $at->extra['first_name'] : '' }} {{ $at->extra['last_name'] }} |
            {{ $at->extra['email'] ? 'Email: ' . $at->extra['email'] : '' }} |
            {{ $at->extra['telephone'] ? 'Tel: ' . $at->extra['telephone'] : '' }}
        @endif
    </option>
@endif @endforeach

我得到了所有结果,并且没有关系。我怎么解决这个问题?条件不起作用。

$attr中我有模型属性数组:

$attrs = Attribute::with('related')->get()->groupBy('attr_id');

3 个答案:

答案 0 :(得分:0)

尝试改变条件来自

@if($at->related)

@if(!empty($at->related))

答案 1 :(得分:0)

执行groupBy('attr_id')时,Laravel Collection会根据ID创建集合的集合。

正确的实现是嵌套的foreach循环来迭代集合。

收集:

$attrCollection = Attribute::with('related')->get()->groupBy('attr_id');

刀片文件:

@foreach($attrCollection as $attr)
    @foreach($attr as $at)
        @if(! is_null($at->related) )
            <option value="{{ $at->related->id }}">
                @if($at->value)
                    {{ $at->related->value }}
                @else
                    {{ $at->related->extra['first_name'] ? 'First Name and Lastname: ' . $at->related->extra['first_name'] : '' }} {{ $at->related->extra['last_name'] }} |
                    {{ $at->related->extra['email'] ? 'Email: ' . $at->related->extra['email'] : '' }} |
                    {{ $at->related->extra['telephone'] ? 'Tel: ' . $at->related->extra['telephone'] : '' }}
                @endif
            </option>
        @else
            <option value="{{ $at->id }}">
                @if($at->value)
                    {{ $at->value }}
                @else
                    {{ $at->extra['first_name'] ? 'First Name and Lastname: ' . $at->extra['first_name'] : '' }} {{ $at->extra['last_name'] }} |
                    {{ $at->extra['email'] ? 'Email: ' . $at->extra['email'] : '' }} |
                    {{ $at->extra['telephone'] ? 'Tel: ' . $at->extra['telephone'] : '' }}
                @endif
            </option>
        @endif
    @endforeach
@endforeach

答案 2 :(得分:0)

替换

@if($at->related)

@if(!$at->related->isEmpty())