J
J
Jedi2020-05-13 09:33:31
Laravel
Jedi, 2020-05-13 09:33:31

How to write Relationships correctly?

I have three tables, I need to link them together, but I don't know how to do it correctly. User

tables



  • id
  • name


Purchases

  • id
  • car_id
  • subscription_id
  • type (String - subscription | car )
  • (Foreign)
  • user_id


Cars

  • id
  • name


Subscription

  • id
  • name


How to write Relationships so that I get the cars bought by the user?

Is it possible so? $user->purchases->cars? In the user model (hasMany), we get all purchases by user_id, and then separate where type = subscriptionand where type = car.

I wrote (helped by the docs) as follows, but one thing, we do not match by type .

return $this->hasManyThrough(
            'App\Car',
            'App\Purchase',
            'id',
            'id',
            'id', 
            'id'
        );


Give advice, please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vism, 2020-05-13
@PHPjedi

Of course you can.
make a carsPurchase() relay
hasMany(...)->where('type', Purchase::TYPE__CAR)
and that's it. all along the docks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question