2017-09-26 60 views
0

我試圖檢索所有'節假日'結合'HolidayInfo'這是各自的表名稱列表。雄辯的關係WHERE語句不起作用

這是我試圖使用查詢:

$holidays = Holidays::with('info')->where('country', $country)->get(); 

當使用這種查詢;我得到以下錯誤:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country' in 'where clause' (SQL: select * from `holidays` where `country` = australia)" 

看來,如果聯接尚未執行。即使寫作'holiday_info.country',它仍然不能按預期工作。

在做的$holidays = Holidays::with('info')->get();一個vardump我得到這個:

enter image description here

這是明顯的關係正在建立,但不包括在查詢中。

這裏是正在使用的表格:

enter image description here enter image description here

我的口才型號:

假日

protected $table = 'holidays'; 
protected $primaryKey = 'holiday_id'; 
public $timestamps = false; 
public $incrementing = false; 
public function info(){ 
    return $this->hasOne('App\HolidayInfo', 'holiday_id','holiday_id'); 
} 

假日信息:

protected $table = 'holiday_info'; 
public $timestamps = false; 
protected $primaryKey = null; 
public $incrementing = false; 
public function holidays(){ 
    return $this->belongsTo('App\Holiday', 'holiday_id', 'holiday_id'); 
} 

我不知道爲什麼兩個表之間的連接不在頂部查詢中工作。看起來好像country沒有被認爲是holiday_info中的一個字段,因此顯示連接沒有正確完成。任何想法可能是什麼問題?

+0

你用錯誤的列名(「國家」)檢查嘗試再次在holiday_info表中有 有一列叫做國家 –

+0

嗨@GauravGupta表格在那裏顯示給你看。該國拼寫正確。 –

+0

嘗試從'belongsTo'語句中的'Holiday Info'模型中刪除一個'holiday_id',然後嘗試! –

回答

3

我認爲它的代碼可以幫助你

$holidays = Holidays::whereHas('info', function($info) use($country){ 
    $info->where('country', $country);    
})->get(); 

Eloquent Relationship

+0

就像一個魅力。做得好 - WhereHas和With有什麼區別? –

+0

'where'和'with'是完全不同的。 'with'用於急切加載,'whereHas'用於關係檢查是否存在。 – linuxartisan

0

試試這個方法。你必須使用功能的加入和使用WHERE條件在它

$holidays = Holidays::with(['info' => function($query) use($country){ 
      $query->where('country', $country); 
     } ])->get(); 
+0

你好,不幸的是,它仍然沒有工作,因爲當我做'$國家='dadadasdas''它仍然返回每一行(當每行不具有該條目) –

+0

你在查詢中添加了'use($ country)'嗎? –

+0

是的。即使我把它做成' - >哪裏('國家','dadasdsa');'它顯示所有條目 –