mohammad hossein
mohammad hossein

Reputation: 49

Laravel morphedByMany Query Returns NULL

I have this model

class Permission extends Model
{

      public function details(): MorphToMany
    {
        return $this->morphedByMany('App\Models\Details', 'model', 'model_has_permissions', 'permission_id', 'model_id');

    }
}

class Details extends Model
{

   public function permission()
    {

    return $this->morphedByMany('App\Models\Permission','model','model_has_permissions','model_id','permission_id');
    }
}

I'm execute this query

Details::with('permission')->find(55);

and got empty array

why happen this?and what is the correct query?

Upvotes: 1

Views: 997

Answers (2)

Wreigh
Wreigh

Reputation: 3287

I don't think it's possible to chain find after with. Here are your options.

  1. Lazy Loading.

    Details::find(55)->load('permissions');
    
  2. Eager loading with where clause

    Details::with('permissions')->where('id', 55)->get();
    

UPDATE

Shouldn't this be morphToMany?

public function details(): MorphToMany
{    
    return $this->morphedByMany('App\Models\Details', 'model', 'model_has_permissions', 'permission_id', 'model_id');
}

Or this?

public function permission()
{
    return $this->morphedByMany('App\Models\Permission','model','model_has_permissions','model_id','permission_id');
}

Upvotes: 0

FULL STACK DEV
FULL STACK DEV

Reputation: 15941

You have a typo in your permission() method

change this

return $this->morphedByMany('App\Models\Permission','model','.model_has_permissions','model_id','permission_id');

to this

return $this->morphedByMany('App\Models\Permission','model','model_has_permissions','model_id','permission_id');

Upvotes: 1

Related Questions