Laravel ORM Consulting relationships

1

I have three tables and models related to each other and I need to consult the properties whose Environment.Name = 'Dormitorios' and PropertyEnvironment.Value = 2 :

  • App\Property :

    • id
    • address
    • etc
  • Methods:

    public function environments()
    {
        return $this->hasMany('App\PropertyEnvironment');
    }
    
  • App\Environment :

    • id
    • name
  • Methods:

    public function value()
    {
        return $this->hasOne('App\PropertyEnvironment');
    }
    
  • App\PropertyEnvironment :

    • id
    • property_id
    • environment_id
    • value
  • Methods:

    public function environment()
    {
        return $this->belongsTo('App\Environment');
    }
    
    public function property()
    {
        return $this->belongsTo('App\Property');
    }
    

    I think the corresponding query would be something like this:

    SELECT *
    FROM properties p
    INNER JOIN property_environments pe ON pe.property_id = p.id
    INNER JOIN environments env ON pe.environment_id = env.id
    WHERE (env.name = 'Dormitorios')
    AND (pe.value = 2);
    

    Any ideas? I thank you in advance

        
    asked by Maramal 01.03.2018 в 15:28
    source

    1 answer

    1

    I have no way to prove it now but I think this may work:

    $properties = $properties->whereHas('environments', function($query)
    {
        //En esta parte "$query" hace referencia a "PropertyEnvironment"
        $query->where('value', 2);
        $query->whereHas('environment', function($query) .
        {
            //En esta parte "$query" hace referencia a "Enviroment"
            $query->where('name', 'Dormitorios');
        });
    });
    

    EDIT

    I added some comments so that you understand a little better for those who are starting with Laravel and Eloquent

        
    answered by 01.03.2018 / 15:49
    source