staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.15k stars 88 forks source link

use through in sub category table #44

Closed webazinsupp closed 4 years ago

webazinsupp commented 4 years ago

hi a'm use this package and try get sub category of product same below: Category → Has many → Category → Has many → Product

in category model

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

and get parent category of product same this in product model:

public function parentCategory()
    {
        return $this->belongsToThrough(Category::class, [Category::class]);
    }

    /**
     * relation product with category one to many.
     * @return BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

but this error:

Syntax error or access violation: 1066 Not unique table/alias: 'categories' (SQL: select `categories`.* from `categories` inner join `categories` on `categories`.`category_id` = `categories`.`id` where `categories`.`id` = 7 limit 1)

in staudenmeir/eloquent-has-many-deep package use Table Aliases trait but in this package not use, please set this trait in this package

staudenmeir commented 4 years ago

I'll consider it.

In the meantime, you can use the HasOneDeep relationship from the other package:

class Product extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function parentCategory()
    {
        return $this->hasOneDeep(
            Category::class,
            [Category::class.' as alias'],
            ['id', 'id'],
            ['category_id', 'category_id']
        );
    }
}

class Category extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasTableAlias;
}
webazinsupp commented 4 years ago

very very good, tnx for help this work for me

staudenmeir commented 4 years ago

I've released a new version that adds support for table aliases (requires Laravel 6+):

class Product extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;

    public function parentCategory()
    {
        return $this->belongsToThrough(Category::class, [Category::class.' as alias']);
    }
}

class Category extends Model
{
    use \Znck\Eloquent\Traits\HasTableAlias;
}