【问题标题】:Get Object from database by many-to-many relation's Object field通过多对多关系的对象字段从数据库中获取对象
【发布时间】:2018-02-28 00:07:36
【问题描述】:

我正在为 Web 应用程序构建 API。我正在构建的自定义路线之一可用于从数据库中获取所有使用来自特定位置的数据集的报告。目前这条路线有点瓶颈,我正在努力加快速度。

一份报告可以包含多组数据。数据也可以属于多个报告。数据表包含来自另一个(外部)数据库的数据集的所有位置。

为了澄清我的数据库,如下所示:

  Report              pivot table          Data
|-----------|        |-----------|        |-------------|
| Report_id |-------<| Report_id |>-------| Data_id     |
|           |        | Data_id   |        | Location_id |
|-----------|        |-----------|        |-------------|

我编写了以下脚本来使用某个数据集获取所有报告,但我觉得这样做可以更有效。

 $reports = Report::whereIn('id',
                \DB::table('report_data')->select('report_id')->whereIn('data_id',
                    \DB::table('data')->select('id')->where('location_id', '=', $id)
                )
             )->get();

我是否在这里遗漏了一些明显的东西,或者这是最好的方法?

【问题讨论】:

    标签: php mysql laravel eloquent many-to-many


    【解决方案1】:

    在模型中

    数据.php

    public function Report()
    {
    return $this->hasMany('App\Report');
    }
    

    报告.php

    public function Data()
    {
    return $this->belongsToMany('App\Data');
    }
    

    (您还可以在选择查询中指定所有字段应包含哪些字段) 并在控制器中

    // To get reports which are having any data
    $reports1 = Report::whereHas('Data',function($query) use($id){
        $query->select('id');
        $query->where('location_id',$id);
    })->orderBy('id', 'desc')
      ->get();
    
    // To get all reports
    
    $reports2 = Report::with(array('Data'=>function($query)use($id){
        $query->select('id');
        $query->where('location_id',$id);
    }))->orderBy('id', 'desc')
        ->get();
    

    【讨论】:

    • 感谢您的回答!这无疑是一种更好看的方式,尽管在性能方面我没有看到很大的优势。不过,我现在会使用它。
    • 在项目扩展时,提供适当的关系并使用 ORM(而不是 DB 查询)将使您的代码变得简单。使用“with()”可以简化更复杂的查询。如果答案似乎有用。请将其标记为正确
    • 例如。 $data['application'] = Application::with('ApplicationType') ->with('ApplicationChild') ->with('ApplicationChild.District') ->with('ApplicationChild.ElectricalSection') ->with(' ApplicationContractorSupervisorMaster') ->with('ApplicationContractorSupervisorMaster.ContractorSupervisor') ->with('District') ->first();
    猜你喜欢
    • 2012-10-31
    • 2019-09-18
    • 1970-01-01
    • 2017-12-12
    • 2022-01-17
    • 2018-08-02
    • 2018-11-19
    • 2018-12-22
    相关资源
    最近更新 更多