如何在laravel中的数据透视表上应用过滤器?

时间:2014-07-31 17:04:15

标签: laravel-4 eloquent

我有三个具有以下关系的模型

MODEL-1:RecoringSchedule

protected $recording_schedule = 'recording_schedules';

// relationship with processes
public function processes()
{
        return $this->belongsToMany('Process', 'recording_uploads', 'recording_schedule_id', 'process_id');
}

MODEL-2:流程

protected $table = 'processes';
// relationship with recordings
public function recordings()
{
    return $this->belongsToMany('RecordingSchedule', 'recording_uploads');
}

MODEL-3:RecordingUpload

protected $table = 'recording_uploads';

此处model3是包含 id,recording_schedule_id,process_id,created_at,updated_at

的数据透视表

我有一个查询,

$recordings = RecordingSchedule::with('processes')->orderBy('recording_date_time', 'desc')->paginate(50)->toArray()

以上查询返回所有带进程的记录。 现在我如何通过数据透视表中的process_id应用过滤器? 比如process_id = 3

我试过Kousha回答

正在显示

[id] => 35
        [dialin_number] => 9908154124
        [operator_extension] => 121
        [recording_id] => 08631a03109
        [max_duration] => 10
        [recording_date_time] => 2014-07-31 13:06:00
        [status] => ADDED
        [created_by] => 32
        [created_at] => 2014-07-31 12:06:48
        [updated_at] => 2014-07-31 12:14:04
        [processes] => Array
            (
                [0] => Array
                    (
                        [id] => 3
                        [name] => basic
                        [created_at] => 2014-07-10 12:22:06
                        [updated_at] => 2014-07-16 14:06:35
                        [pivot] => Array
                            (
                                [recording_schedule_id] => 35
                                [process_id] => 3
                            )

                    )

            )

以及其他录音如下

[id] => 39
        [dialin_number] => 939938333
        [operator_extension] => 141
        [recording_id] => 123456#
        [max_duration] => 30
        [recording_date_time] => 2014-07-31 12:19:00
        [status] => ADDED
        [created_by] => 32
        [created_at] => 2014-07-31 13:20:16
        [updated_at] => 2014-07-31 13:20:34
        [processes] => Array
            (
            )

    )

在第二个阵列中,显示空进程。实际上,录制属于进程ID 6.我不希望其他录制带有其他进程ID。

提前致谢

1 个答案:

答案 0 :(得分:0)

您不会在数据透视表上应用过滤器,而是在表processes上应用

$process_id = 3;

$recordings = RecodingsSchedule::with([
    'processes' => function($query) use ($process_id)
    {
        $query->whereId($process_id);
    }
])->orderBy('recording_date_time', 'desc')->paginate(50)->toArray();