Php 通过关系进行Laravel搜索
直截了当地说。 我的项目列表上有搜索功能。但是,我也希望按类别搜索所有项目 以下是我到目前为止所做的。 我对拉雷维尔真的很陌生,而且口才很好,所以请容忍我 类别表Php 通过关系进行Laravel搜索,php,laravel-5.3,laravel-eloquent,Php,Laravel 5.3,Laravel Eloquent,直截了当地说。 我的项目列表上有搜索功能。但是,我也希望按类别搜索所有项目 以下是我到目前为止所做的。 我对拉雷维尔真的很陌生,而且口才很好,所以请容忍我 类别表 public function up() { Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string('code', 30);
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('code', 30);
$table->string('name');
$table->softDeletes();
$table->timestamps();
});
}
项目表
public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('code', 30);
$table->string('name');
$table->softDeletes();
$table->timestamps();
});
Schema::table('items', function($table){
$table->foreign('category_id')->references('id')->on('categories');
});
}
这是我的密码:
public function search(){
$q = Input::get ( 'q' );
if($q != ""){
$items = Item::with('Category')
->where ( 'name', 'LIKE', '%' . $q . '%' )
->orWhere ( 'code', 'LIKE', '%' . $q . '%' )
->whereHas('Category', function($cat){
$cat->where('name', 'hardware');
})->paginate(1)->setPath('');
$items = $items->appends ( array (
'q' => Input::get ( 'q' )
) );
}else{
$items = Item::orderBy('id', 'desc')->paginate(10);
}
$softDeletesItems = Item::onlyTrashed()->get();
return view('item.index', compact('items', 'softDeletesItems'));
}
我有没有办法做一个
或where('category.name','LIKE','%.$q'.%')
?以下是我为实现它所做的
$items = Item
::join('categories', 'items.category_id', '=', 'categories.id')
->where ( 'items.name', 'LIKE', '%' . $q . '%' )
->orWhere ( 'items.code', 'LIKE', '%' . $q . '%' )
->orWhere('categories.name', 'LIKE', '%' . $q . '%')
->select('*')
->paginate(1)->setPath('');
你能同时提供项目和类别表列以便我们检查吗?Hi@iCoders给我一秒钟,我会发布它。@iCoders你能再检查一次吗?->where has('category',function($query)use($q){$q){$query->where('name','hardware')->或where('name','LIKE',''.'''.$q.%')@iCoders是的,先生,我有办法做
->或where吗('categories.name'、'LIKE'、'%'.$q'.%')
?
$items = Item
::join('categories', 'items.category_id', '=', 'categories.id')
->where ( 'items.name', 'LIKE', '%' . $q . '%' )
->orWhere ( 'items.code', 'LIKE', '%' . $q . '%' )
->orWhere('categories.name', 'LIKE', '%' . $q . '%')
->select('*')
->paginate(1)->setPath('');