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);
}
}