mercredi 28 octobre 2015

Laravel 5 where clause from another table

I have a simple code and what I want to do is to access a field from another table and put it in my where clause. This is my code:

ReportController.php

$reservations = Reservation::with('room')
-> whereBetween('reservation_from', [$from, $to])
-> where('room.type', \Request::input('type')) //what should this be
-> orderBy('created_at')
-> get();

Room.php

class Room extends Model
{
    use SoftDeletes;
    protected $table = 'rooms';

    protected $fillable = ['id', 'roomNumber', 'type', 'price', 'description'];

    public function reservations() {
        return $this->hasMany('App\Reservation', 'id', 'room_number');
    }
}

Reservation.php

class Reservation extends Model
{
    use SoftDeletes;
    protected $table = 'reservations';

    protected $fillable = ['roomNumber', 'clientId', 'reservation_from', 'reservation_to'];

    public function room() {
        return $this->belongsTo('App\Room');
    }

}

Schema: enter image description here

As you can see in the ReportController.php, there is a comment saying "what should this be", that's the part that I want to fix. What I wanted to do is access the type field in the rooms table in my eloquent query.

Is there a way to do this? Thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire