Relating 3 Standard Tables

Asked

Viewed 38 times

1

Hello. I have a small model attached here. My task is from users, to get the records of Orders that have some record in the payment with the id of that order and the id of that user. Basically, an order can have several payments, which has the order_id and the user_id. and I want to access in my controller $user->Orders. I have tried the relationship hasManyThrough, I did not get results. I would need to create a pivot table to supply my problem?

  • because in the payments you didn’t put voucher_id? That is the name of the convention, of course another name works is that it leaves the standard. Cade its relations and its classes?

  • Puts the models

1 answer

0

Assuming you understand how to relate models in Laravel correctly, you should use Has Many Thogheter.

Thus:


class User
{
    public function orders()
    {
        return $this->hasManyThrough(Order::class, Payment::class);
    }
}

You can find more details in the documentation of the relationship methods.

If you cannot with the above method...

You can use whereHas

$orders = Order::whereHas('payments', function ($query) use($user) {
     return $query->where('user_id', '=', $user->id);
});
  • so I did exactly with hasManyThrough, but I don’t know why there’s a bug in the constrains. I’ll try it with the query.Can I put it in my model? class User { public Function Orders() { Return Order:whereHas('Payments', Function($query) use($user) { Return $query->Where('user_id', '=', $user-id); }); } a};}

  • You can set the values of the fields in the other through parameters... I mean, if the column does not have in the internal Laravel convention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.