Answer the question
In order to leave comments, you need to log in
How to make a relationship between 3 tables?
Good afternoon, how can I organize a relationship between 3 tables.
I have 3 tables, a machine, a machine component directory, and a damage directory.
I can’t link all these 3 tables together in any way, so that it would be convenient to select them.
For example auto->getComponents->getDamagers();
I tried to link all this through a separate table, car_has_damage, where I assigned 3 fields, car_id, component_id, damage_id.
But ran into a problem
foreach ($car->components as $component) {
echo $component->name;
foreach ($component->getDamages($car->id) as $damages) {
echo $damage->name;
}
}
$damage->name; "Trying to get property of non-object"
//Car model
public function getComponents(){
return CarComponent::find()->all();
}
// Component model
public function getDamages($id)
{
return $this->hasMany(Damage::className(),['id' => 'damage_id'])->viaTable('car_has_damage', ['component_id' => 'id'], function($query)use($id) { $query->onCondition(['car_id' => $id]); });
}
Answer the question
In order to leave comments, you need to log in
Good evening.
To get started, start by checking what you pass to foreach().
Something like this:
This is not correct
If you already pass a parameter, then first pass, get the result, and then pass it to foreahc ()
$component = $component->getDamages($car->id)
foreach($component as $damages){
****************
}
public function getCity()
{
return $this->hasOne(Cities::className(), ['id' => 'city_id']);
}
$test = new RoutesCities(['city_id' => 1]);
echo "<pre>";
print_r($test->getCity());
print_r($test->city);
foreach ($component->getDamages($car->id) as $damages) { echo $damage->name; }
you need it in the singular, you just, as always, do what you need in the singular in the plural, some kind of talent right there :)
that's how you need it:
UPD: Why doesn't your IDE highlight errors for you?
UPD: I see you have some kind of problem. I highly recommend that you watch the video on links in Yii2, very sensible, I even sketched a menu there (in the comments)
https://www.youtube.com/watch?v=URlo4QjNNao
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question