سؤال

I have models like this:

  1. have a table (product_types) of product types.
  2. have a table (products) of products with a many-to-one relationships to the product types table.
  3. have a table (attribute_types) of attribute types.
  4. have a table of (many-to-many) relationships between product types and attribute types
  5. have a table (attributes) containing attribute type, attribute value.
  6. have a table of (many-to-many) relationships between products and attributes.

There are a few main things I need to do with this collection

$product_type = ProductType::find(1);

Find all the products for a product type.

return $product_type->products;

Find all the attribute types for a product type

return $product_type->attribute_types;

Find all the attributes for the attribute type and product type. I know the problem here is I need attributes to be the children of product type and attribute type.

But, I'm not sure the best way to do this.

هل كانت مفيدة؟

المحلول

Setup relations like in docs http://laravel.com/docs/eloquent#relationships

Then you can get collection you want like this:

//return $product_type->products;
$product_type->load('products')->products; // returns Eloquent Collection of products
// or shorter equivalent:
$product_type->products;

//return $product_type->attribute_types;
the same as above since the relationships are identical (many-to-many)


// Then to get Attributes:
$product_type->load('products.attributes');
//then you can get all attributes as a single array (every attr as an array not model):
$attributesArray = $product_type->products->fetch('attributes')->collapse();

// or without casting merge all Attributes in a loop:
$attributesCollection = new \Illuminate\Database\Eloquent\Collection;
foreach ($product_type->products as $product)
{
  $attributesCollection = $attributesCollection->merge($product->attributes);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top