Skip to content

eager load ancestors/descendants on related model #271

Open
@ashgibson

Description

@ashgibson

I have a data structure with Products and Categories (nested set) but these models are scoped to an account_id. How can get a product and eager load the category and descendants or ancestors?

Due to the scope, I can see the query is adding scope with account_id = NULL.

$products = Product::with('category.ancestors')->get();
class Product extends Model {

   protected $guarded = [
      'id',
   ];

   public function account() {
      return $this->belongsTo( Account::class );
   }

  public function category() {
     return $this->belongsTo(Category::class);
  }
}
class Category extends Model {

   use NodeTrait;

   protected $guarded = [
      'id',
      NestedSet::LFT,
      NestedSet::RGT,
      NestedSet::PARENT_ID
   ];

   protected function getScopeAttributes() {
      return [ 'account_id' ];
   }

   public function account() {
      return $this->belongsTo( Account::class );
   }

  public function products() {
     return $this->hasMany(Product::class);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions