lundi 31 octobre 2016

How to retrieve Nested Relationship data in laravel 5 using eloquent?

Having some problems retrieving nested relationship data. Here are my models:

Partner Model

class Partner extends Model
{
    public function admins()
    {
         return $this->hasMany(Resource::class)->where('resource_type', 'Admin');
    }
}

Resource Model

class Resource extends Model
{
    public function details() {
        return $this->belongsTo(ResourceDetail::class);
    }
}

ResourceDetail Model

class ResourceDetail extends Model
{
}

When I try $this->partner->admins[0]->details it's giving null. The sql it generated is: "select * from resource_details where resource_details.id is null". I'm not quite sure why is it null in the query. I must have done something wrong with the relations. I tried $this->partner->with('admins.details')->find($this->partner->id)->toArray();. It's getting the admins, but details is still null. I also tried hasManyThrough, like: return $this->hasManyThrough(ResourceDetail::class, Resource::class)->where('resource_type', 'Admin'); it finds "unknown column". This is my database structure:

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');
});

Do I need to change the structure? Or, how can I get the data from current structure? All I want is, a partner has many resources, and a resource has one details.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire