【问题标题】:Eloquent relation WHERE statement not working雄辩的关系 WHERE 语句不起作用
【发布时间】:2017-09-26 06:09:51
【问题描述】:

我正在尝试检索所有 'Holidays' 与 'HolidayInfo' 组合的列表,它们是各自的表名。

这是我尝试使用的查询:

    $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 时,我明白了:

这里很明显正在建立关系,但未包含在查询中。

以下是正在使用的表格:

我的雄辩模型:

节假日

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');
}

我不确定为什么两个表之间的连接在顶部查询中不起作用。似乎国家没有被识别为 holiday_info 中的字段,因此显示连接没有正确完成。任何想法可能是什么问题?

【问题讨论】:

  • 你使用了错误的列名('country')检查再试一次在holiday_info表中有一个名为country的列
  • 嗨@GauravGupta,表格在那里显示供您查看。国家拼写正确。
  • 尝试在Holiday Info 声明中从Holiday Info 模型中删除一个holiday_id。然后试试看!

标签: php mysql sql laravel eloquent


【解决方案1】:

我认为它的代码可能会对你有所帮助

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

Eloquent Relationship

【讨论】:

  • 工作就像一个魅力。干得好 - WhereHas 和 with 有什么区别?
  • whereHaswith 完全不同。 with 用于预先加载,whereHas 用于关系检查是否存在。
【解决方案2】:

试试这个方法。您必须使用函数来加入并使用其中的 where 条件

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

【讨论】:

  • 您好,不幸的是它仍然不起作用,因为当我创建 $country = 'dadadasdas' 时它仍然返回每一行(当每一行没有该条目时)
  • 您是否在查询中添加了use($country)
  • 是的。即使我做到了->where('country', 'dadasdsa');,它也会显示所有条目
猜你喜欢
  • 2015-05-17
  • 2014-09-20
  • 2023-04-07
  • 2019-08-13
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多