How to set up HasManyThrough relationship with foreign keys only in the intermediate table?

I’m working on a project using Laravel v9.19 and PHP 8.0.

Here is a part of that project’s database which is relevant to the question:

  • One user can have many orders, but each order has only one user (one-to-many relationship).
  • One order can have only one item, but one item may be present in many orders (many-to-one relationship).

Here is a User class:

class User extends Authenticatable
{
    // ...

    /**
     * Get orders of this user.
     * 
     * @return IlluminateDatabaseEloquentRelationsHasMany
     */
    public function orders(): HasMany
    {
        return $this->hasMany(Order::class, 'client_id');
    }
}

Here is an Order class:

class Order extends Model
{
    // ...

    /**
     * Get the client of this order.
     * 
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function client(): BelongsTo
    {
        return $this->belongsTo(User::class, 'client_id');
    }

    /**
     * Get the ordered item.
     * 
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function item(): BelongsTo
    {
        return $this->belongsTo(Item::class, 'item_id');
    }
}

Here is an Item class:

class Downloadable extends Model
{
    // ...

    /**
     * Get the orders having this item.
     * 
     * @return IlluminateDatabaseEloquentRelationsHasMany
     */
    public function orders(): HasMany
    {
        return $this->hasMany(Order::class, 'item_id');
    }
}

I would like to utilize the Eloquent Relationships in order to make it possible to:

  • Retrieve all items ordered by a specific user.
  • Retrieve all users that ordered a specific item.

I will need to add a new method to the User model:

    /**
     * Get items ordered by this user.
     * 
     * @return ???
     */
    public function items()
    {
        // What to do here?
    }

I will need to add a new method to the Item model:

    /**
     * Get users that ordered this item.
     * 
     * @return ???
     */
    public function users()
    {
        // What to do here?
    }

Since the default HasManyThrough relationship requires a different table structure, and I cannot modify the existing table structure, it’s not applicable here.

As one of possible solutions I’m considering to use staudenmeir/eloquent-has-many-deep, creating a new intermediate table named order_item to map orders to items, and use the following code, for example, for the items method:

    /**
     * Get items ordered by this user.
     * 
     * @return ???
     */
    public function items()
    {
        return $this->hasManyDeep(
                    Item::class,
                    [Order::class, 'order_item']
            );
    }

If there exists a Laravel solution without external libraries, or you know something more efficient, please share that to me. I’m eager to know the best practice for that case.

2

The relationship you have defined is a belongsToMany relationship, but if you’re set on using hasManyThrough, purely to retrieve the other set you could use:

class User extends Authenticatable
{
    // ...

    /**
     * Get all items ordered by the user.
     * 
     * @return IlluminateDatabaseEloquentRelationsHasManyThrough
     */
    public function items(): HasManyThrough
    {
        return $this->hasManyThrough(Item::class, Order::class, 'client_id', 'id', 'id', 'item_id');
    }
}
class Item extends Model
{
    // ...

    /**
     * Get all users who ordered this item.
     * 
     * @return IlluminateDatabaseEloquentRelationsHasManyThrough
     */
    public function users(): HasManyThrough
    {
        return $this->hasManyThrough(User::class, Order::class, 'item_id', 'id', 'id', 'client_id');
    }
}

However if you are look to create Orders through the relationship you should use the belongsToMany

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật