简体   繁体   中英

Laravel database relationships not working

What am I doing wrong here?

My entradas table:

Schema::create('entradas', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('categoria_id');
            $table->string('descricao', 200);
            $table->double('valor');
            $table->timestamps();
        });

My categorias table:

Schema::create('categorias', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('titulo', 100);
            $table->enum('tipo', ['debito', 'credito']);
            $table->timestamps();
        });

My Entrada model:

public function categoria()
    {
        return $this->belongsTo('App\Categoria');
    }

My Categoria model:

public function entradas()
    {
        return $this->hasMany('App\Entrada');
    }

Returning this on my EntradaController :

public function index() {
        return(Entrada::find(1));
    }

I get the following result:

{
    "id": 1,
    "categoria_id": 3,
    "descricao": "Distinctio minus praesentium quia ea voluptatem pariatur et. Tenetur maiores mollitia molestias asperiores. Exercitationem maiores voluptas id dolore rerum unde. Ipsum dolorem facere aut ut quos.",
    "valor": 108,
    "created_at": "2020-02-17 17:49:36",
    "updated_at": "2020-02-17 17:49:36"
}

Why don't I get the categoria property?

Try updating your foreign key column definition like so:

Schema::create('entradas', function (Blueprint $table) {
    // ...
    $table->bigInteger('categoria_id')->unsigned();
    //                                ^^^^^^^^^^^^^
    // You could also do:
    // $table->unsignedBigInteger('categoria_id');
    // ...
});

Also, to access the relationship you need to load it. So as an answer to this

Why don't I get the categoria property?

You could make use of Eager Loading :

public function index()
{
    return Entrada::with('categoria')->find(1);
}  //               ^^^^^^^^^^^^^^^^

This should give you the expected json:

{
    "id": 1,
    "categoria_id": 3,
    "descricao": "Distinctio minus praesentium quos.",
    "valor": 108,
    "categoria": {
        // ...
    },
    "created_at": "2020-02-17 17:49:36",
    "updated_at": "2020-02-17 17:49:36"
}

You have to eager load your categoria property in order to get it, like this:

public function index () {
    return Entrada::with('categoria')->find(1);
}

More info in the docs here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM