2
votes

Currently I have three tables one is property table having following columns:

  • id
  • name
  • description

2nd is tags table having following colums:

  • id
  • tag_name
  • tag_status

3rd is the pivot table having following columns:

  • id
  • tag_id
  • property_id

Now in Property Model I have defined the relation with pivot table like this:

 public function tags()
    {
        return $this->belongsToMany('Tag');
    }

and in Tag Model I have defined the relation with pivot table like this:

public function properties()
    {
        return $this->belongsToMany('Property');
    }

Now what I need to now is how can I write the following query on these three tables using eloquent ORM of Laravel:

 $propertyTags=Property::join('property_tag', 'properties.id', '=', 'property_tag.property_id')
             ->join('tags', 'tags.id', '=', 'property_tag.tag_id')
             ->where('properties.id','=',$property_id)
             ->get(['tags.tag_name','tags.id']);
1

1 Answers

0
votes

you can try

$property_obj = Property::find($property_id);
$property_tags = $property_obj->tags->all();

or using eager loading

$property_with_tags = Property::with('tags')->where('id','=',$property_id)->get();