2017-09-26 63 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');'它显示所有条目 –