Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0
// for clarity I suggest renaming your relation to plural on ProductCategory model:
public function products()
{
   return $this->hasMany('Product','category');
}
// although it doesn't change how the things work


// then this way you get the category and related products 
$category = ProductCategory::with('products')->where('ref_title','=',$idcag)->first(array('name','id'));
$category->products; // Collection of Product models

// which is basically the same as this, as long as you get only one category first:
$category = ProductCategory::where('ref_title','=',$idcag)->first(array('name','id'));
$products = $category->products;

// Now these lines do exactly the same:
$products = $category->products; // Eloquent will know that it will need to run this:
$products = $category->products()->get(); // if it wasn't retrieved before

So the only thing you shouldn't have done is

ProductCategory::find($datas->id)

since this queries productcategories table once again.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

rezadaulay rezadaulay Joined 25 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.