Home > Blockchain >  Laravel: Retrieve records from a table with an associated table via another table
Laravel: Retrieve records from a table with an associated table via another table

Time:12-14

here is my problem.

I have 3 tables:

  1. bookings (id, spot_id,...)

a booking have one spot and a spot have multiple bookings

  1. spots (id, place_id,...)

a spot have one place and a place have multiple spots

  1. places(id, ...)

And what i want is from the BookingController get a list of bookings with their associated places

somethings like that:

Booking::where("ok",1)->with("place")->get();

i already have the "hasMany" and "belongsTo" relations in all three models. And i already tried "hasOneThrough" in booking model but to no avail.

how can i do that thanks.

CodePudding user response:

If you always want to have the places included in the booking model you can add those as an attribute:

namespace App\Models;

class Booking{
    public $appends = ['places'];

    public function getPlacesAttribute()
    {
        return $this->hasMany(Place::class);
    }
}

Now you can acces places directly from the booking class like $booking->places

  • Related