简体   繁体   中英

Laravel - restrict query through relations?

I've been hitting my head against the wall with this, so I need a bit of help. I'm using Laravel 4.2.4. I have two models, Event and EventDate.

// Event has id, name
class Event extends Eloquent
{
    protected $table = 'events';
    protected $guarded = ['id'];
    public $timestamps = false;

    public function eventdates()
    {
        return $this->hasMany('\EventDate', 'event_id', 'id');
    }
}

// EventDate has id, event_id, start_date, end_date
class EventDate extends Eloquent
{
    protected $table = 'eventdates';
    protected $guarded = ['id'];
    public $timestamps = false;
}

Now I'm trying to get Events between a certain start and end date. So according to the docs, I should be able to do:

\Event::with('eventdates')->where('start_date', '>=', '2014-01-01')->where('end_date', '<=', '2014-02-01')->get();

But all that does is throw an SQLSTATE[42S22]: Column not found: 1054 Unknown Column 'eventdates.start_date' in 'where clause' .

I've also tried using Closures (if using the repository pattern) such as:

return $this->model->with(['eventdates' => function($query) use ($startDate, $endDate) {
    $query->where('start_date', '<=', $endDate->format('Y-m-d'));
    $query->where('end_date', '>=', $startDate->format('Y-m-d'));
}]);

This feels like a really dumb error, but I can't figure it out. Any ideas?

You may try this:

$events = \Event::with(array('eventdates' => function($query){
    // Querying in the eventdates table
    $query->where('start_date', '>=', '2014-01-01')
          ->where('end_date', '<=', '2014-02-01');
}))->get();

It's because start_date and end_date fields are available in the eventdates table.

I can more or less answer this question. I had better success using whereHas:

return $this->model->whereHas('eventdates', function($query) use ($startDate, $endDate) {
    $query->where('start_date', '<=', $endDate->format('Y-m-d'));
    $query->where('end_date', '>=', $startDate->format('Y-m-d'));
})
->with('eventdates');

Thanks, all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM