How to relate Models the correct way in laravel?

0

You see, I'm working with 3 models, the property, the type of property and the location of the property, it happens that the type of property and the location of the property are attributes of the property (it should be noted that they are in relation one to one, that is, a property has only one type of property and only one location), the problem is that I do not know how to relate them in the correct way in Laravel, for example when creating a property, I want a form in your form that shows the existing options in the table (database) of types of real estate, that is to say if in the table of the database I have:

  • Option one
  • Option two
  • Option three
  • In the select should leave these same options available

    I would also like someone to explain to me more thoroughly the use of methods that return things like:

    return $this->hasOne('App\Phone', 'foreign_key');

    These are the methods of defining a relationship, such as One to many, many to many or one to one (I attach the laravel documentation: link )

    I did not understand Laravel's documentation very well and I did not understand how these methods should be used, thank you very much.

        
    asked by Santiago Bueno 11.12.2018 в 22:30
    source

    1 answer

    0

    Having a 1-1 relationship requires the use of the hasOne at the time of accessing the relationships, for example having the Real Estate Model you would have two functions there which refer to which is related to the other two models.

    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class Inmobiliaria extends Model
    {
    /*
     * Relación con la ubicación.
     */
     public function Ubicacion()
     {
        return $this->hasOne('App\Ubicacion','ubicacion_id');
     }
    /*
    Acá especificas que tiene relación con las opcion especifica
    */
     public function Opcion()
     {
        return $this->hasOne('App\Opciones','opcion_id');
     }
    }
    

    With this in the model the laravel will know that when accessing the instance of that object will bring the relationship:

    $inmobiliaria = Inmobiliaria::find(1);
    $Ubicacion    = $inmobiliaria->Ubicacion;
    $Opcion       = $inmobiliaria->Opcion;
    

    You can also use the eager loading which consists of doing a load and avoiding the error n +1, it would be something like that

    $inmobiliaria = Inmobiliaria::with('Ubicacion', 'Opcion')->get();
    /*Haciendo esto ya nuestras relaciones vienen cargadas y evitamos hacer una consulta con cada petición o acceso a la relación*/
    foreach ($inmobiliaria as $valor) {
     echo $valor->Ubicacion; /*para acceder al nombre solo debes colocar acceso a la propiedad $valor->Ubicacion->name*/
     echo $valor->Opcion;
    }
    
        
    answered by 11.12.2018 / 22:55
    source