staudenmeir / belongs-to-through

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

How can I get list of related tables? #46

Closed mjza closed 3 years ago

mjza commented 4 years ago

How can I get list of tables that are belongs to? something like getThroughParents that gives all the related tables.

staudenmeir commented 4 years ago

There is no such method at the moment. I'll look into adding one.

mjza commented 4 years ago

Sorry I am in a hard development and I really need this function. What is your estimation regarding the time that it will be finished.

mjza commented 4 years ago

If you add all the functions that we have in hasManyDeep library here it would be grate.

mjza commented 4 years ago

Hi. I extended your class and solved my issue. If you like you can use the code. Unfortunately have no time to make a pull request. I will put the code here.

<?php

namespace App\Relations;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Znck\Eloquent\Relations\BelongsToThrough AS BelongsToThroughParent;

class BelongsToThrough extends BelongsToThroughParent
{
    /**
     * Create a new belongs to through relationship instance.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param \Illuminate\Database\Eloquent\Model $parent
     * @param \Illuminate\Database\Eloquent\Model[] $throughParents
     * @param string|null $localKey
     * @param string $prefix
     * @param array $foreignKeyLookup
     * @return void
     */
    public function __construct(Builder $query, Model $parent, array $throughParents, $localKey = null, $prefix = '', array $foreignKeyLookup = [])
    {
        parent::__construct($query, $parent, $throughParents, $localKey, $prefix, $foreignKeyLookup);
    }

    public function getThroughParents(){
        return $this->throughParents;
    }

    public function getPrefix(){
        return $this->prefix;
    }

    /**
     * Get the foreign key for a model.
     *
     * @return string[]
     */
    public function getForeignKeys()
    {
        $models = $this->throughParents;
        $foreignKeys = [$this->getForeignKeyName($this->getRelated())];
        foreach($models as $model){
            array_push($foreignKeys, $this->getForeignKeyName($model));
        }
        return $foreignKeys;
    }

    /**
     * Get the foreign key for a model.
     *
     * @return string[]
     */
    public function getLocalKeys()
    {
        $models = $this->throughParents;
        $foreignKeys = [$this->getRelated()->getKeyName()];
        foreach($models as $model){
            array_push($foreignKeys, $model->getKeyName());
        }
        return $foreignKeys;
    }
}