Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

HUGE_DICK_10_INCHES's avatar

Correct many to many relation

I am really confused here, I have 3 tables:

Users: id, name Stocks: id, user_id, name Reservations: id, user_id, stock_id

User hasMany reservations, Stock hasMany reservations, Reservation belongsTo User and Stock.

But how can I get All reservations where stock_id as id in stocks table has user_id of current logged user:

I tried:

public function requested() {
        return $this->belongsToMany('App\Reservation', 'stocks', 'user_id', 'user_id');
}

But it returns empty collection. Do I need to run custom raw query or is there correct relation?

public function requested() {
        return $this->hasManyThrough('App\Reservation', 'App\Stock', 'user_id', 'stock_id');
    }

This works but as user_id I get always current user model id, for all entries....

From tinker: App\User::find(422)->requested

 all: [
       App\Reservation {#2997
         id: 12,
         stock_id: 3,
         user_id: 422, // Current user model id 
         amount: 2,
         accepted: 0,
         done: 0,
         delivered_at: "0000-00-00 00:00:00",
         created_at: "2019-02-12 11:00:36",
         updated_at: "2019-02-12 11:00:36",
       },
     ],

And in database I have:

id => 12, stock_id => 3, user_id => 420

Same goes for multiple entries in database with different user ids, in laravel all user_ids switched with current model user id

In simple words I would need this:

$reservations = [];

foreach(App\Reservation::all() as $reservation) {
    if($reservation->stock->user->id === auth()->user()->id) {
        array_push($reservations, $reservation);
    }
}
0 likes
5 replies
shez1983's avatar

i think the correct example is that BOTH one specific user & stock has reservation.. since a reservation requires both things..

users,
stocks,
reservations:  user_id,  stock_id, ....

then you will have

function reserved_stock()  { //relatuonship on User table

return $this->belongsToMany('App\Stock', 'reservations', 'user_id', 'user_id');
}

and a similar one called reserved_by on stock..

then you can do \Auth::user()->reserved_stock.. should give you all stock being reserved by a user

shez1983's avatar

just because that returns empty collection doesnt mean its incorrect.. i dont believe u need hasManyThrough but obv you have discarded my opinion so continue on...

Snapey's avatar

how can I get All reservations where stock_id as id in stocks table has user_id

Nonsensical question, but why not

$reservations = Auth::user()->stocks()->reservations()->get();

Please or to participate in this conversation.