【问题标题】:Laravel search from two tablesLaravel 从两个表中搜索
【发布时间】:2016-06-20 13:33:50
【问题描述】:

我想制作一个搜索引擎,它可以按行“名称”在合作伙伴表客户中按给定名称搜索,但无法弄清楚我应该如何制作它...目前搜索引擎工作完美,但我只能通过两列搜索我已经描述了。当我尝试添加列名“名称”时,它说变量未定义

这是我的模型 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'));
    }

【问题讨论】:

  • 你能把你尝试过但最终没有用的东西包括在内吗?

标签: php laravel search


【解决方案1】:

试试这个:

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

这基本上搜索您的 client 关系 name 列。

【讨论】:

    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多