Closed maelga closed 3 years ago
@staudenmeir Isn't a HasOneThorugh
the opposite of the BelongsToThrough
?
If we assume a table structure like
User
- id
Category
- id
- user_id
Item
- id
- category_id
With the relations
class Category {
public function user() {
return $this->belongsTo(User::class);
}
}
class Item {
public function category() {
return $this->belongsTo(Category::class);
}
}
then I would assume I could retrieve an item's user using
class Item {
public function user() {
return $this->belongsToThrough(User::class, Category::class);
}
}
which hasOneThrough
does not do. For hasOneThrough
to work, the User
would need to have one category_id
instead of the Category
having the user_id
(unless I'm missing something - if it's possible, I'd be eager to know how!).
By default, HasOneThrough
is the opposite of BelongsToThrough
, but you can achieve the same result by swapping foreign and local keys.
Hello, I have a problem, I retrieved the right model, but this is always with a key ID from the intermediate, (example : It throw an error like "No model App\Price matches the ID 1151"). I tried with hasOneThrough
class Shooting {
public function customer() {
return $this->belongsTo(
'App\Customer',
);
}
public function price() {
return $this->hasOneThrough(
'App\Price',
'App\Customer',
'id', // Foreign key on customers table...
'id', // Foreign key on prices table...
'customer_id', // Local key on shootings table...
'price_id' // Local key on customers table...
);
}
}
And with your belongsToThrough Method
class Shooting {
public function customer() {
return $this->belongsTo(
'App\Customer',
);
}
public function price() {
return $this->belongsToThrough(
'App\Price', 'App\Customer',
);
}
}
class Customer {
public function price() {
return $this->belongsTo(
'App\Price',
);
}
}
Any idea ?
@Quendi6 You are having this issue with both hasOneThrough()
and belongsToThrough()
, right?
Yes, exactly
What versions of Laravel and the plugin are you using?
Moving this to new issue
Laravel 5.8 added
HasOneThrough
that you can use to defineBelongsToThrough
relationships with a single intermediate model.Deeper relationships are probably too much of an edge case.