Laravel雄辩的查询加入

时间:2016-03-22 10:27:27

标签: laravel

<?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创建一个客户端拥有的机器列表,我需要让这个列表只显示OSNAME字段中带有word服务器的机器,我已经尝试过如下操作,但它也无法正常工作

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

我不确定这样做的正确的laravel方法是什么,我应该创建一个新模型吗?

客户端/机器在DB中引用2个不同的表。

1 个答案:

答案 0 :(得分:1)

使用预加载过滤器:

<强>之前:

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);
}

<强>后:

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);
}   

请参阅:https://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads

正确的方法(避免不必要的查询):

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);
}