【问题标题】:Laravel 4.1 querying hasMany relationship?Laravel 4.1查询hasMany关系?
【发布时间】:2014-06-21 04:02:24
【问题描述】:

我的问题是关于在 Laravel 4.1 / ORM 中查询关系。

我有一个“实验室”模型和一个“日期”模型。两者配置为具有 2 路关系:

日期.php:

  public function lab(){
    return $this->belongsTo('Labs');
  }

Labs.php:

  public function dates() {
    return $this->hasMany('Dates');
  }

在我的控制器中,我想查询我的实验室,并获取日期为 $today 的实验室:

$today = new DateTime('today');
$activeLab = Labs::hasDate($today);
return $activeLab;

类似的东西……但这当然行不通。

如何检索它拥有的日期与我提供的日期匹配的“实验室”?

感谢您的帮助!

编辑:额外的代码进度..

$today = new DateTime('today');
$today = $today->format('Y-m-d');
$activeLab = Labs::whereHas('dates', function($q) use ($today){
        $q->where('dates.date', $today);
    })->get();

return $activeLab;

最终编辑 - 解决方案:

感谢 deczo,我们能够确定问题所在。默认情况下,Eloquent 使用模型名称链接到外键。我的模型名为 Labs(复数),因此它在 dates 表中查找 labs_id。可以在Labs模型hasMany()语句中指定外键:

public function dates() {
  return $this->hasMany('Dates', 'lab_id');
}

【问题讨论】:

    标签: php mysql laravel laravel-4


    【解决方案1】:
    $search; // value to find
    
    Lab::whereHas('dates', function ($q) use ($search) {
       $q->where('dates.someColumn', $search);
    })->get();
    

    它将返回Labs,并在给定WHERE子句的情况下匹配相关日期。

    更改Labs上的关系:

    public function dates() {
      return $this->hasMany('Dates', 'lab_id');
    }
    

    【讨论】:

    • 这会为我抛出一个 QueryException:Column not found: 1054 Unknown column 'dates.labs_id' in where clause (SQL: select * from labs where (select count(*) from dates where dates.labs_id = labs.id and dates.date = 2014-06-20) >= 1)
    • 你应该有lab_id。无论如何显示你的代码。
    • deczo,我已经用代码编辑了原始帖子。 lab_id 也确实存在于 Dates 表中,这是一个错字,我很抱歉。
    • 我注意到它在寻找dates.labs_id,拼写应该是dates.lab_id——不知道为什么要添加复数s?
    • 对于hasMany,Eloquent 使用模型名称来猜测外键,并且由于您的模型是复数,因此它会查找 labs_id
    猜你喜欢
    • 2015-12-22
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2019-01-23
    • 2019-06-02
    相关资源
    最近更新 更多