Search code examples
eloquentlaravel-5.4relationships

Generate Model relationship in laravel 5.4


I have 3 table & model:

1) product
-----------
id, name, c_id, sku

2) category
----------
id, name, parent_c_id

3) parent_category
-----------------
id, name

How to get product detail with category and parent category using eloquent relationship?


Solution

  • Eloquent let's you define relationships with between your models/tables inside your model classes. To define that a model has a foreign key, you can use belongsTo to define that your model belongs to another model.

    // Product.php
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
    
    // Category.php
    public function category()
    {
        return $this->belongsTo('App\ParentCategory');
    }
    

    Eloquent will look for a column named <lowercase modelname>_id in the database table. For Product that would mean category_id, as Product belongs to Category.

    If you don't want to change your column names, you can define the foreign key as the second argument:

    return $this->belongsTo('App\Category', 'c_id');
    

    You can read up on these relationships in the Laravel Docs


    Update #1

    It looks like I misunderstood your question a little, so based on your comment, I think this should work:

    Product::with('category')
        ->with('category.parent_category')
        ->get();