Catch All Records and Separate by Status

2

Dealer.php

class Dealer extends Model
{

    # Relacionamento com Medalhas
    public function dealer_medalhas(){
        return $this->hasMany('App\DealerMedal', 'id_concessionaria');
    }
}

DealerMedal.php

class DealerMedal extends Model
{
    # Relacionamento com Medalhas
    public function dealer(){
        return $this->belongsTo('App\Dealer');
    }
}

I have a relationship that I'm doing in Laravel. This query brings all the medals that a store has. But I also want to bring the medals that the store does not have in the same query.

And separate by status, type:

SHOP 1 --- MEDAL 1 --- TEM
SHOP 1 --- MEDAL 2 --- TEM
SHOP 1 --- MEDAL 3 --- DO NOT HAVE

The way the last line is, it does not come because of the relationship.

I want them all to come.

The query:

# Pesquisar na Base de Dados a Consulta do Usuário
$consulta       = Dealer::whereIdMarca($codMarca)
                  ->whereIdCidade($codCidade)
                  ->where('concessionaria', 'like', '%'.$concessionaria.'%')
                  ->whereStatus(1)
                  ->get();
    
asked by anonymous 15.03.2016 / 20:31

2 answers

2

Thinking quickly here, I can do this by separating in two queries.

$dealer = Dealer::find($id);

$medalhas_que_tem = $dealer->dealer_medalhas()->get();

$medalhas_nao_tem = DealerMedals::whereDoesntHave('dealer', function ($query) use($id)
{
      $query->where('id', '=', $id);

})->get();

The get method returns the Illuminate\Support\Collection method, which in turn has the merge method.

If you need the two results together, you can do it.

$dealers = $medalhas_nao_tem->merge($medalhas_que_tem);
    
15.03.2016 / 21:18
1

I solved it, in the same logic.

@foreach($res->dealer_medalhas as $item => $key)
    <?php 
        $arrM['id'][$key->medalhas->id]      = $key->medalhas->id;
        $arrM['medalha'][$key->medalhas->id] = $key->medalhas->medalha;
        $arrM['icon'][$key->medalhas->id]    = $key->medalhas->icon;
    ?>
@endforeach
<?php unset($medalhas[0]); ?>
@foreach($medalhas as $foo => $bar)
    @if(in_array($foo, $arrM['id']))
        <div class="badges" data-order="1" data-medalha="{!! $arrM['id'][$foo] !!}">
            {!! Html::image('images/medalhas/'.$arrM['icon'][$foo].'-on.png', $arrM['medalha'][$foo]) !!}
        </div>
    @else
        <?php 
            if($foo == 1)     $icon = 'medalha-melhor-preco-off.png';
            elseif($foo == 2) $icon = 'medalha-melhor-atendimento-off.png';
            elseif($foo == 3) $icon = 'medalha-melhor-servico-off.png';
        ?>
        <div class="badges" data-order="0" data-medalha="{!! $foo !!}">
            {!! Html::image('images/medalhas/'.$icon, $bar) !!}
        </div>
    @endif
@endforeach
    
16.03.2016 / 14:19