流畅地查询以下场景

时间:2013-11-04 21:40:48

标签: php mysql laravel-4 eloquent

我有一个数据库中的程序列表。每个程序都有一个程序所属的organization_id,以及start_dateend_date

我的问题是,如果给出了两个日期,那么查询应该怎么样?我必须得到所有在日期之间开始或在特定组织的日期之间结束的程序。以下查询返回超出组织范围(不属于组织)的所有程序。

<?php

DB::table('programs')
    ->where('organization_id', $organizationidlist[0])
    ->whereBetween('start_date', array($start_date, $end_date))
    ->orWhere(function ($query) use($start_date, $end_date, $organizationidlist) {
        $query
            ->where('organization_id', $organizationidlist[0])
            ->whereBetween('end_date', array($start_date, $end_date))
        ;
    })
    ->orderBy('created_at', 'desc')
    ->get()
;

?>

1 个答案:

答案 0 :(得分:1)

为什么不用滔滔不绝的模特呢? Laravel拥有如此优秀的数据模型系统。您可以通过以下方式轻松完成您想要的任务:

Organization::find($id)->projects()->where('start_date', '>', $start)->where('end_date', '<', $end)->orderBy('created_at', 'desc')->get();

http://laravel.com/docs/eloquent

相关问题