2016-11-27 174 views
1

我試圖做一個搜索查詢,即搜索服務標題,描述和公司名稱(公司有服務,如果公司名稱匹配,它會返回服務)。Laravel搜索查詢

我有一個搜索字段,傳遞給我的控制器。 我已經嘗試過這樣的:

$query = Service::select('id','company_id','title','description',price); 
$search = $request->input('search',null); 
$query = is_null($search) ? $query : $query->where('title','LIKE','%'.$search.'%')->orWhere('description','LIKE','%'.$search.'%')->orWhereHas('company', function ($q) use ($search) 
    { 
     $q->where('name','LIKE','%'.$search.'%')->get(); 
    }); 


$services= $query->paginate(5); 

但我得到一個錯誤,在未知列'services.company_id 'where子句'(SQL:SELECT * FROM companies其中servicescompany_id = companiesidname。 LIKE%xx%和companiesdeleted_at爲空)

我該怎麼做這個搜索?

謝謝!

更新:

class Service extends Model 
{ 
use SoftDeletes; 

protected $dates = ['deleted_at']; 

public function company() { 

    return $this->belongsTo('Company'); 

} 
} 

class Company extends Model 
{ 
    use SoftDeletes; 

    protected $dates = ['deleted_at']; 

    public function services() { 
    return $this->hasMany('Service'); 
} 
} 

Schema::create('services', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('company_id'); 
     $table->integer('service_category_id'); 
     $table->integer('server_id'); 
     $table->string('title'); 
     $table->string('description'); 
     $table->string('icon'); 
     $table->boolean('accepts_swaps'); 
     $table->integer('qty_available'); 
     $table->double('price_usd', 10, 6); 
     $table->timestamps(); 
     $table->softDeletes(); 
    }); 

Schema::create('companies', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('owner_id'); 
     $table->string('name'); 
     $table->string('email'); 
     $table->string('paypal_email')->nullable(); 
     $table->string('skrill_email')->nullable(); 
     $table->string('contact_email')->nullable(); 
     $table->string('phone')->nullable(); 
     $table->integer('city_id')->nullable(); 
     $table->string('short_description')->nullable(); 
     $table->text('description')->nullable(); 
     $table->integer('subscription_id')->nullable(); 
     $table->timestamp('subscription_end_date')->nullable(); 
     $table->string('avatar')->default("img/default/user-avatar-128.min.png"); 
     $table->integer('highlighted_game_id')->nullable()->default(null); 
     $table->timestamps(); 
     $table->softDeletes(); 
    }); 
+0

有你'companies'表'company_id'列? – piotr

+0

你可以在你的問題中顯示你的表格模式和關係嗎?更新了 –

+0

,請檢查它。謝謝! – user3844579

回答

2

在where子句引起該問題的get功能。嘗試通過刪除get

所以你的代碼會看:

$query = Service::select('id','company_id','title','description',price); 
$search = $request->input('search',null); 
$query = is_null($search) ? $query : $query->where('title','LIKE','%'.$search.'%')->orWhere('description','LIKE','%'.$search.'%')->orWhereHas('company', function ($q) use ($search) 
    { 
     $q->where('name','LIKE','%'.$search.'%'); 
    }); 


$services= $query->paginate(5); 
+0

謝謝,現在工作! – user3844579

+0

很高興幫助... –