检索嵌套关系数据时遇到一些问题。这是我的模特:
class Partner extends Model
{
public function admins()
{
return $this->hasMany(Resource::class)->where('resource_type', 'Admin');
}
}
class Resource extends Model
{
public function details() {
return $this->belongsTo(ResourceDetail::class);
}
}
class ResourceDetail extends Model
{
}
当我尝试$this->partner->admins[0]->details
时,它会给出null。它生成的sql是:"select * from resource_details where resource_details.id is null"
。我不太确定为什么在查询中它为null。我必须对这些关系做错了。我试过了$this->partner->with('admins.details')->find($this->partner->id)->toArray();
。它获得了管理员,但细节仍为空。我还尝试了hasManyThrough
,例如:return $this->hasManyThrough(ResourceDetail::class, Resource::class)->where('resource_type', 'Admin');
它找到"未知列"。这是我的数据库结构:
Schema::create('partners', function (Blueprint $table) {
$table->increments('id');
});
Schema::create('resources', function (Blueprint $table) {
$table->increments('id');
$table->integer('partner_id')->nullable()->unsigned();
$table->foreign('partner_id')->references('id')->on('partners')
->onUpdate('cascade')->onDelete('set null');
$table->enum('resource_type', constants('RESOURCE_TYPES'))->nullable();
$table->integer('resource_detail_id')->unsigned();
$table->foreign('resource_detail_id')->references('id')->on('resource_details')
->onUpdate('cascade')->onDelete('cascade');
});
Schema::create('resource_details', function (Blueprint $table) {
$table->increments('id');
});
我需要更改结构吗?或者,我如何从当前结构中获取数据?我想要的只是,合作伙伴有很多资源,资源有一个细节。
答案 0 :(得分:0)
根据该错误,我认为您可能会尝试从没有ID的模型中调用$this->partner->admins[0]->details
。上下文中的$this
是什么?