Stacey
Stacey

Reputation: 67

Laravel Fetching one to Many Relationship

Hello I am learning laravel and I am having an issue retrieving data from my relations.

In my database there are Product and Groups filled with dummy data.

I defined my relationship like this in product model:

     public function Group()
        {
     return $this->hasMany('App\Groups','product_id', 'id');
      }

And in my group vice versa with :

      public function Product()
      {
      return $this->belongsTo('App\Product','product_id', 'id');
      }

The way I am referencing to my products table is :

     $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

Now I have column product_id in my database under groups, and it is linked to if from products id it seems.

The groups table contains of its auto incremented id and product_id foreign key column.

While products table has auto incremented id and name column.

The issue is here : How do I return the products that are not null or have value (of products id) in groups table.


I tried something like this in my filter controller:

        public function getProductsWithGroup()
{

      $Products = Product::with('groups')->get();
     return $Products ;

}

But that is giving me call to undefined relations.

I am not sure how to access belongsTo or hasMany methods and whether I need an extra group_id column in my products table.

Upvotes: 1

Views: 2618

Answers (1)

Ijas Ameenudeen
Ijas Ameenudeen

Reputation: 9259

You named the relationship wrong. It should be groups & define in lowercase as

public function groups()
{
    return $this->hasMany('App\Groups','product_id', 'id');
}

And use ->has() to check existence

public function getProductsWithGroup()
{
    $Products = Product::has('groups')->get();
    return $Products ;
}

->with() is used to eager load and ->has() is used to check existence & filter.

To get the products don't have any groups,

$Products = Product::doesntHave('groups')->get();

To see other ways to use ->has() check, https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence

Upvotes: 1

Related Questions