[英]Laravel database relationships not working
What am I doing wrong here?我在这里做错了什么?
My entradas
table:我的entradas
表:
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:我的categorias
表:
Schema::create('categorias', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('titulo', 100);
$table->enum('tipo', ['debito', 'credito']);
$table->timestamps();
});
My Entrada
model:我的Entrada
模型:
public function categoria()
{
return $this->belongsTo('App\Categoria');
}
My Categoria
model:我的Categoria
模型:
public function entradas()
{
return $this->hasMany('App\Entrada');
}
Returning this on my EntradaController
:在我的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?为什么我没有得到categoria
属性?
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 :您可以使用Eager Loading :
public function index()
{
return Entrada::with('categoria')->find(1);
} // ^^^^^^^^^^^^^^^^
This should give you the expected json:这应该给你预期的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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.