hasOneThrough and hasManythrough Relationship Example in Laravel
Hello Artisan it's a little bit confusing to understand laravel hasmanythrough relationship. In this example i will discuss about laravel hasmanythrough example and we will try to understand when we can use laravel hasmanythrough relationship. In this example we will see has one through and has many through relationship example.
Look the “has one through” relationship links models through a single intermediate eloquent relation. Assume that the situation where each product has one supplier and each product has one product history record. Then for this situation the supplier model can access the product history record through the product.
Has one through
This is what the database tables look like:
suppliers:
- id
products:
- id
- supplier_id
product_history:
- id
- product_id
Even though the product_history
table doesn’t contain a supplier_id
column, the supplier can get access to the product_history
record by using a “has one through” relationship.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Supplier extends Model
{
public function productHistory() {
return $this->hasOneThrough(App\History::class, App\Product::class);
}
}
Has many through
The “has many through” eloquent relationship is the equivalent of the “has one through” relationship, but for multiple records. Let’s use the previous example to understand better, but we change one thing: a product can now have multiple history entries instead of one. The database tables remain the same.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Supplier extends Model
{
public function productHistory() {
return $this->hasManyThrough(App\History::class, App\Product::class);
}
}
This way the supplier model can get access to the history entries of the product. Hope it can help you.