V
V
vrazbros2020-01-15 23:24:18
Laravel
vrazbros, 2020-01-15 23:24:18

How can you get values ​​if you use a one-to-many relationship?

In Laravel, I use two User entities that can have several different Transport values. A one-to-many relationship is used. The Transport table contains information about the user's transport.
The transport table contains three columns:

UserId, ParamName, ParamValue:
 1 |  car |  'audi'
 1 |  bicicle | 'ufo'
 2 | car | 'bmv'
 2 | track | 'man'
 3 | ship |  'cruize'

In the User model, added a one-to-many relationship to the transport table
public function transports() : HasMany
{
$this->hasMany(Transport::class, 'UserId', 'Id');
}

and now in the code i get all the user's transport something like this:
$user = User::find(1);
$transports = $user->transports()->get();
foreach($transports as $transport)
{
  echo $transport->ParamName;
  echo $transport->ParamValue;
}

but I have to iterate through all the data, but how, for example, to get the name of the user's machine with id =1 ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question