Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sebastian.virlan's avatar

Get data from Relation Tables

If I have properties table, and other 2 tables

  • property_characteristics

    • property_id (i.e. 1)
    • characteristic_id (i.e. 5 - join with default_characteristics)
    • value (i.e. 3 - aka 3 rooms)
  • default_characteristics

    • id (i.e. 5)
    • name (i.e. rooms)

How can I get the number of rooms (value from property_characteristics) for a property if I set up all belongs_to and has_many in models?

    $property = Properties::find(1);
0 likes
3 replies
sebastian.virlan's avatar

@willvincent I think something is wrong here:

Property.php model

    public function property_characteristics()
    {
        return $this->hasMany('Proactiv\PropertyCharacteristic', 'property_id', 'id');
    }

DefaultCharacteristic.php mode

    public function default_characteristic()
    {
        return $this->belongsTo('Proactiv\DefaultCharacteristic', 'characteristic_id', 'id');
    }

Is this enough?

Or I need something like this:

    public function property_characteristics()
    {
        return $this->belongsToMany('Proactiv\DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id');
    }
sebastian.virlan's avatar
Level 1

I solved with:

    public function characteristics()
    {
        return $this->belongsToMany('Proactiv\DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id')
            ->withPivot('value');
    }

And method:

    public function getCharacteristic($name)
    {
        $value = $this->characteristics
                    ->where('name', $name)
                    ->first();
        if(!$value) return '?';
        return $value
            ->pivot
            ->value;
    }

Please or to participate in this conversation.