如果关系是一对多,为什么belongsTo返回数组?
IlluminateDatabaseEloquentCollection {#1288
#items: array:1 [
0 => AppModelsBrand {#1289
#connection: "mysql"
#table: "brands"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:4 [
"id" => 16
"title" => "tenetur"
"created_at" => "2022-03-09 18:54:32"
"updated_at" => "2022-03-09 18:54:32"
]
#original: array:4 [
"id" => 16
"title" => "tenetur"
"created_at" => "2022-03-09 18:54:32"
"updated_at" => "2022-03-09 18:54:32"
]
....
我知道hasMany((关系会返回一个模型,所以为了尝试和错误,我在我的Item模型上为hasOne更改了belongsTo,似乎希望Brands表有一个Item_id,但这没有意义。
一件物品只有一个品牌。一个品牌会有很多商品。
项目
+----------+----------------------------------------+-------+
| brand_id | sku | price |
+----------+----------------------------------------+-------+
| 1 | Wuckert, Russel and Murray | 6.52 |
| 2 | McGlynn Group | 34.69 |
| 2 | Walker-Murphy | 86.57 |
| 4 | Langworth PLC | 1.61 |
+----------+----------------------------------------+-------+
品牌
+----+--------------+---------------------+---------------------+
| id | title | created_at | updated_at |
+----+--------------+---------------------+---------------------+
| 1 | impedit | 2022-03-09 18:54:32 | 2022-03-09 18:54:32 |
| 2 | sit | 2022-03-09 18:54:32 | 2022-03-09 18:54:32 |
| 3 | tenetur | 2022-03-09 18:54:32 | 2022-03-09 18:54:32 |
| 4 | odio | 2022-03-09 18:54:32 | 2022-03-09 18:54:32 |
+----+--------------+---------------------+---------------------+
我的模型是这样定义的。
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Brand extends Model
{
use HasFactory;
/**
* Get the items associated with the brand.
*/
public function items()
{
return $this->hasMany(Item::class);
}
}
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Item extends Model
{
use HasFactory;
/**
* Get the brand associated with the item.
*/
public function brand()
{
return $this->belongsTo(Brand::class);
}
}
错误来自于使用方括号的方式。尝试作为
$newitem->brand;
Doku:一旦定义了关系,我们就可以使用Eloquent的动态属性来检索相关记录。动态属性允许您访问关系方法,就好像它们是在模型上定义的属性一样: