【发布时间】:2020-07-20 07:11:13
【问题描述】:
以下是所有模型、迁移和控制器。
捐赠模式
class Donation extends Model
{
protected $guarded =[];
public function users(){
return $this->hasMany(User::class);
}
public function items(){
return $this->belongsTo(DonationItems::class);
}
}
捐赠物品模型:
class DonationItems extends Model
{
protected $guarded=[];
public function donation(){
return $this->hasMany(Donaition::class);
}
}
捐赠物品迁移:
public function up()
{
Schema::create('donation_items', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->timestamps();
});
}
捐赠迁移:
public function up()
{
Schema::create('donations', function (Blueprint $table) {
$table->id();
$table->string('item');
$table->unsignedInteger('user_id');
$table->unsignedInteger('donation_item_id');
$table->timestamps();
});
}
在我的控制器中,我想访问以下项目:
$don = Donation::all();
$don->items;
但我无法做到这一点。
【问题讨论】:
-
这是你的要求吗:捐赠有很多物品,一个物品属于一个捐赠?这里还有一个类型: return $this->hasMany(
Donaition::class) 你有一个额外的i -
@user3532758 是的,我发现了错字,我想知道用户捐赠了一些东西,所以它属于哪个类别项目,或者它是一种食品医疗服务。
-
为什么不试试急切加载。 laravel.com/docs/7.x/eloquent-relationships#eager-loading。试试
Donation::with('items')->get()另外,DontationItems 类中的donation关系应该是belogsTo关系。 -
你打错字了,需要这样调用
$don = Donation::find(1); $don->items; -
@user3532758 尝试急切加载 `{{$donnor->categories->category}}' 但是当我这样做时,在我看来它没有给我我的必填字段它显示此错误 此集合实例上不存在属性 [类别]。