Search and bring id of another table

1

The problem search field is working, but I would like to search for the client name as they are related.

search method in controller

public function busca(OrdemRequest $request)
{
    $problema = $request->problema;
    $ordens = Ordem::where('problema', 'LIKE', "%{$problema}%")->get();
    return view('ordem.listaordens',compact('ordens'));
}

Route:

Route::post('/busca','OrdemController@busca');

View:

<form action="/ordem/busca"method="post">   
    <div class="form-group">
        {{csrf_field()}}
        <input type="text" class="form-control" name="problema" placeholder="Buscar...">

Order Model:

class Ordem extends Model
{

    protected $fillable = ['id','cliente_id','valor','data','problema','servico_id'];
    protected $table = 'ordens'; 
    public function produto()
    {
        return $this->belongsToMany(produto::class, 'produto_id');
    }
    public function servico()
    {
        return $this->belongsTo(servico::class,'ordem_id','servico_id');
    }
    public function cliente()
    {
        return $this->belongsTo(Cliente::class,'cliente_id');
    }   
}

Client Model:

class Cliente extends Model
{
    protected $fillable = ['id','nome','cpf','endereco','telefone','email'];
    protected $table = 'clientes';
    public function ordem()
    {
        return $this->hasMany(ordem::class,'cliente_id');
    
asked by anonymous 01.12.2018 / 17:49

1 answer

0

When you need to do a search type that has a relationship, use the Query Builder join method of the following form:

public function busca(OrdemRequest $request)
{
    $problema = $request->problema;
    $ordens = Ordem::join('clientes', 'clientes.id','=','ordems.cliente_id')
        ->where('clientes.nome', 'LIKE', "%{$problema}%")
        ->get();
    return view('ordem.listaordens',compact('ordens'));
}

This makes the relation of the tables and having the possibility of using filters in fields referring to the relations.

Another way would also be whereExists as follows:

public function busca(OrdemRequest $request)
{
    $problema = $request->problema;
    $ordens = Ordem::whereExists(function($query) use($problema)
       {
           $query->select(\DB::raw(1))
                 ->from('clientes')
                 ->whereRaw('clientes.id = ordems.cliente_id')
                 ->where('clientes.nome','LIKE',"%{$problema}%")
       })  
        ->get();
    return view('ordem.listaordens',compact('ordens'));
}

References :

02.12.2018 / 14:59