【问题标题】:In Laravel Eloquent, select "whereIn" from parent table在 Laravel Eloquent 中,从父表中选择“whereIn”
【发布时间】:2015-09-28 04:52:31
【问题描述】:

在我的 Laravel 项目(使用 MySQL 数据库)中,我有几个模型:Time EntriesTasksProjects。 p>

时间条目属于任务

任务属于项目

所以每个表都包含对应其父级 ID 的列。

我有一组 项目 ID,我正在尝试通过他们的 任务 选择属于那些的 时间条目项目。

换句话说,我希望能够做这样的事情:

$timeEntries = TimeEntry::whereIn('project_id',$projectIds)->get();

但很明显,我得到一个 column not found 错误,因为我在 time entries 表中得到的只是 task_id 而不是 project_id.

有没有办法在单个 Eloquent 查询中选择所需的时间条目(基于我拥有的项目 ID)?非常感谢您的帮助。

【问题讨论】:

    标签: php mysql laravel eloquent laravel-5


    【解决方案1】:

    在您的项目模型中添加以下方法

    public function timeEntries()
    {
        return $this->hasManyThrough('App\TimeEntry' , 'App\Task');
    }
    

    现在您可以获得如下项目的所有时间条目

    $project = Project::find(id);
    $project->timeEntries()->get();
    

    【讨论】:

      【解决方案2】:

      所以您要解释的关系类型是通过关系 (http://laravel.com/docs/5.1/eloquent-relationships#has-many-through)。

      而不是尝试从项目->任务->时间条目中向上树向下树。

      Projects::whereIn($projectIds)->with('time_entries')->get();
      

      生成的集合将是具有(应该至少)一个名为 time_entries 字段的项目,每个项目中都有所有相关时间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-01
        • 2017-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-03
        • 2017-10-02
        • 1970-01-01
        相关资源
        最近更新 更多