Laravel从两个表

时间:2016-06-20 13:33:50

标签: php laravel search

我希望制作搜索引擎,按行和#34;名称"在合作伙伴关系表客户端中按给定名称搜索但是无法弄清楚我该怎么做...现在搜索引擎工作得很完美,但我只能搜索我描述的两列。当我尝试添加列名称' name'它说变量是未定义的

这是我的模型Client.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Client extends Model {
    protected $fillable = [
        'name',
        'nip',
        'telephone',
        'email',
        'address'
    ];
    public function licenses() {
        return $this->hasMany('App\License');
    }
}

这是我的型号License.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class License extends Model {
    protected $fillable = [
        'productName',
        'licenseNumber',
        'fvNumber',
        'buyDate',
        'other',
        'client_id'
    ];
    public function client() {
        return $this->belongsTo('App\Client');
    }
}

和我的控制器

<?php
namespace App\Http\Controllers;
use Request;
use DB;
use App\Http\Requests;
use App\Http\Requests\CreateLicenseRequest;
use App\License;
use App\Client;

class LicensesController extends Controller {
    public function index() {
        $licenses = License::get();
        $search = \Request::get('search'); 
        $licenses = License::where('productName','like','%'.$search.'%')
            ->orWhere('licenseNumber','like','%'.$search.'%')
            ->orderBy('id')
            ->paginate(20);
        return view('admin.crm.licenses.all',compact('licenses'));
    }

1 个答案:

答案 0 :(得分:3)

试试这个:

$licenses = License::where('productName','like','%'.$search.'%')
    ->orWhere('licenseNumber','like','%'.$search.'%')
    ->orWhereHas('client', function ($query) use ($search) {
        $query->where('name', 'like', '%'.$search.'%');
    })
    ->orderBy('id')
    ->paginate(20);

这基本上会搜索您的客户端关系名称列。