dev7
dev7

Reputation: 183

Laravel eloquent query join

<?php

namespace App\Http\Controllers;

use App\Clients;
use Illuminate\Http\Request;
use App\Http\Requests;

class AuditsController extends Controller {

    public function index() {
        $clients = Clients::distinct()->select('tag')->where('tag', '!=', 'NA')->get();
        return view('clients', compact('clients'));
    }

    public function show($client) {
        $machines = Clients::with('machines', 'bios')->where('TAG', $client)->get();
        $server = $machines->where('OSNAME', 'LIKE', '%server%')->get();

        return view('audit', compact('client'))->with('server', $server);
    }

}

$machines creates a list of machines the client has, i need to have this list only show the machines with the word server in the field OSNAME, ive tried doing it as follows but it also did not work

$machines = Clients::with('machines', 'bios')->where('TAG', $client)->where('OSNAME', 'LIKE', '%server%')->get();

I'm not sure on what is the correct laravel method for doing this, should i create a new model?

Clients/machines reference 2 different tables in DB.

Upvotes: 0

Views: 43

Answers (1)

Mysteryos
Mysteryos

Reputation: 5791

Use Eager-loading Filters:

Before:

public function show($client) {
    $machines = Clients::with('machines', 'bios')->where('TAG', $client)->get();
    $server = $machines->where('OSNAME', 'LIKE', '%server%')->get();

    return view('audit', compact('client'))->with('server', $server);
}

After:

public function show($client) {
    $machines = Clients::with(['machines' => function($query) {
        //Filter eager loaded relation
        return $query->where('OSNAME', 'LIKE', '%server%');
    }, 'bios'])->where('TAG', $client)->get();

    return view('audit', compact('client'))->with('machines', $machines);
}   

See: https://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads

The Right Way (Avoids unnecessary queries):

public function show($client) {
    //Proper way to do it
    $server = Machine::whereHas('client',function($query) use ($client){
        return $query->where('TAG', $client)
    })->where('OSNAME', 'LIKE', '%server%')->get();

    return view('audit', compact('client'))->with('server', $server);
}

Upvotes: 1

Related Questions