ネストされた関係データを取得する際にいくつかの問題があります。ここに私のモデルは以下のとおりです。熟語を使用してlaravel 5のネストされたリレーションシップデータを取り出す方法は?
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
をしようとします。生成されたSQLは"select * from resource_details where resource_details.id is null"
です。私はなぜそれがクエリでnullであるのかはよく分かりません。私は関係に何か悪いことをしたに違いない。私は$this->partner->with('admins.details')->find($this->partner->id)->toArray();
を試しました。それは管理者を取得していますが、詳細はまだnullです。私もhasManyThrough
のように試しました:return $this->hasManyThrough(ResourceDetail::class, Resource::class)->where('resource_type', 'Admin');
"unknown column"が見つかりました。これは私のデータベース構造です:
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');
});
構造を変更する必要はありますか?または、どのようにして現在の構造からデータを取得できますか?私が望むのは、パートナーには多くのリソースがあり、リソースには1つの詳細があります。
'$ this-> partner-> admins() - > first() - > details'についてはどうですか? – Wistar
null。私はそれが '$ this-> partner-> admins [0] - > details'と同じだと思います –