staudenmeir / belongs-to-through

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

How create custom localKeyLookup for alias? #97

Closed erycson-cubo closed 7 months ago

erycson-cubo commented 7 months ago

I have a specific situation, which I try to exemplify with the code below. What I'm trying to do is use a specific "localKeyLookup" for my alias, but unfortunately I couldn't, I would like to know if there is any way to solve this problem in a more elegant way

class User extends Model {
  public function products()
  {
      return $this->belongsToThrough(
          Product::class,
          [SubscriptionProduct::class, Subscription::class, SubscriptionProduct::class . ' as sp'],
          foreignKeyLookup: [SubscriptionProduct::class => 'id'],
          localKeyLookup: [
              SubscriptionProduct::class => 'subscription_id',
              'sp' => 'user_id',
          ],
      );
  }
}

For now, I tried to solve the problem like this, but it didn't work::

class User extends Model {
  public function products()
  {
      $alias = new class extends ProductSubscription
      {
          protected $table = 'product_subscription';
      };

      return $this->belongsToThrough(
          Product::class,
          [ProductSubscription::class, Subscription::class, $alias::class . ' as sp'],
          foreignKeyLookup: [ProductSubscription::class => 'id'],
          localKeyLookup: [
              ProductSubscription::class => 'subscription_id',
              $alias::class => 'user_id',
          ],
      );
  }
}

My database has these relationships, and my intention is, from the user, to obtain all the products that he has subscribed to directly, remembering that I need to go through the subscriptions table to be able to obtain the current valid subscription:

graph TD;
    product_subscription-->users;
    product_subscription-->subscriptions;
    product_subscription-->products;
erycson-cubo commented 7 months ago

I solved it using the following method:

public function products()
    {
        return $this->belongsToMany(Product::class, ProductSubscription::class)
            ->join('subscriptions', 'subscriptions.id', 'product_subscription.subscription_id');
    }