skip to Main Content

I want to retrieve all places where parent_place_id = 999 in the attractions table. What relationships would I set up and what would this query look like?

I’ve tried using the "Has Many Through" relationship, but I’m not sure if this applies, as my relationship is between two tables, not three.

I have a table places, with columns:

id place_id name
1 999 New York
2 1000 Miami
3 1001 Houston

And a second table, attractions:

id place_id parent_place_id
1 1000 999
2 1001 999

2

Answers


  1. class Place extends Model
    {
        public function attractions()
        {
            return $this->hasMany(Attraction::class, 'parent_place_id', 'place_id');
        }
    }
    
    
    class Attraction extends Model
    {
        public function place()
        {
            return $this->belongsTo(Place::class, 'place_id', 'id');
        }
    }
    

    Then you can retrieve all places where parent_place_id is equal to 999 from the attractions table.

    $placesWithAttractions = Place::whereHas('attractions', function ($query) {
        $query->where('parent_place_id', 999);
    })->get();
    
    Login or Signup to reply.
  2. class Place extends Model
    {
        public function attractions()
        {
            return $this->hasMany(Attraction::class, 'parent_place_id', 'place_id');
        }
    }
    
    class Attraction extends Model
    {
        public function place()
        {
            return $this->belongsTo(Place::class, 'place_id', 'id');
        }
    }
    

    Then you can call it with a method like this:

    $places = Place::whereRelation('attractions', 'parent_place_id', 999)->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search