Laravel Eloquent search multiple fields and relationship

时间:2018-02-15 12:30:11

标签: php laravel laravel-eloquent

I am trying to create a search query so that I can search the same string across a few different fields. The query also needs to search fields from the machine_warranties which is setup as a hasOne relationship on the Machines model.

Here's the warranty relationship in the Machines model

public function warranty()
{
    return $this->hasOne('App\MachineWarranty', 'machine_id');
}

Here's my attempt at the query. Searching for a serial or machine type works fine but I cannot figure out how to also search the relation.

Machine::orderBy('created_at', 'desc')
  ->where('serial', 'LIKE', '%' . $search . '%')
  ->orWhere('type', 'LIKE', '%' . $search . '%')
  ->with(['warranty' => function($query) use ($search) {
       $query->where('first_name', 'LIKE', '%' . $search . '%');
  }]);

Is there a way to do ->orWith() maybe?

2 个答案:

答案 0 :(得分:2)

使用orWhereHas()方法:

Machine::latest()
    ->where('serial', 'like', '%' . $search . '%')
    ->orWhere('type', 'like', '%' . $search . '%')
    ->orWhereHas('warranty', function($q) use($search) {
        $q->where('first_name', 'like', '%' . $search . '%');
    })
    ->get();

答案 1 :(得分:1)

使用whereHas()进行and查询:

Machine::orderBy('created_at', 'desc')
->where('serial', 'LIKE', '%' . $search . '%')
->orWhere('type', 'LIKE', '%' . $search . '%')
->with('warranty')
->whereHas('warranty' , function($query) use ($search) {
   $query->where('first_name', 'LIKE', '%' . $search . '%');
})->get();