staudenmeir / belongs-to-through

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

Any reason why this relationship didn't make it to the framework? #50

Closed maelga closed 3 years ago

staudenmeir commented 4 years ago

Laravel 5.8 added HasOneThrough that you can use to define BelongsToThrough relationships with a single intermediate model.

Deeper relationships are probably too much of an edge case.

tklie commented 3 years ago

@staudenmeir Isn't a HasOneThorugh the opposite of the BelongsToThrough?

If we assume a table structure like

User
- id

Category
- id
- user_id

Item
- id
- category_id

With the relations

class Category {
  public function user() {
    return $this->belongsTo(User::class);
  }
}

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

then I would assume I could retrieve an item's user using

class Item {
  public function user() {
    return $this->belongsToThrough(User::class, Category::class);
  }
}

which hasOneThrough does not do. For hasOneThrough to work, the User would need to have one category_id instead of the Category having the user_id (unless I'm missing something - if it's possible, I'd be eager to know how!).

staudenmeir commented 3 years ago

By default, HasOneThrough is the opposite of BelongsToThrough, but you can achieve the same result by swapping foreign and local keys.

Quendi6 commented 3 years ago

Hello, I have a problem, I retrieved the right model, but this is always with a key ID from the intermediate, (example : It throw an error like "No model App\Price matches the ID 1151"). I tried with hasOneThrough

class Shooting {
    public function customer() {
        return $this->belongsTo(
            'App\Customer',
        );
    }
    public function price() {
        return $this->hasOneThrough(
                    'App\Price',
                    'App\Customer',
                    'id', // Foreign key on customers table...
                    'id', // Foreign key on prices table...
                    'customer_id', // Local key on shootings table...
                    'price_id' // Local key on customers table...
                );
    }
}

And with your belongsToThrough Method

class Shooting {
    public function customer() {
        return $this->belongsTo(
            'App\Customer',
        );
    }
    public function price() {
        return $this->belongsToThrough(
            'App\Price', 'App\Customer',
        );
    }
}

class Customer {
    public function price() {
        return $this->belongsTo(
            'App\Price',
        );
    }
}

Any idea ?

staudenmeir commented 3 years ago

@Quendi6 You are having this issue with both hasOneThrough() and belongsToThrough(), right?

Quendi6 commented 3 years ago

Yes, exactly

staudenmeir commented 3 years ago

What versions of Laravel and the plugin are you using?

Skintillion commented 3 years ago

Moving this to new issue