Jump to content

How do I transform the result of an Inner Join in 2 classes?


robsonrdasilva

Recommended Posts

Hey, what's up?

 

I've the fallowing function which return an array of Products with the type Product:

 

public function get_products()
{
$sql = 'SELECT * FROM products';
$query = mysql_query($sql);

return mysql_fetch_object($query, 'Product');
}

 

But now I need return a list of Products and for each product a category, so I'm changing the sql:

 

SELECT products.*, categories.name as category_name FROM products INNER JOIN categories ON products.id_category = categories.id_category

 

How do I make it?

 

My class Product doesn't have the fields of Category.

 

Thanks.

Not exactly sure what you are trying, but I hope this example helps..

 

$sql = "SELECT products.*, categories.name as category_name FROM products INNER JOIN categories ON products.id_category = categories.id_category";

class Test
{
function getCategoryAndProduct()
{
	echo $this->category_name . ' - ' . $this->product_name . '<br>';
}
}

$result = mysql_query($sql);

while ($testObject = mysql_fetch_object($result, 'Test'))
{
$testObject->getCategoryAndProduct();
}

So, I didn't know that it works in php.

You only created a class called Test without fields and PHP brought all fields of database.

But, unfortunately I need create my class with all fields, the same fields of table Products.

 

class Product
{
   private $id_product;
   private $id_category;
   private $name;
}

class Category
{
   private $id_category;
   private $name;
}

 

How do I match a Category with a Product?

Do I need to create a field in class Product called category with type "Category"?

 

Or in class Category I put an array of products?

 

Thanks

I can't really test anything right here now, coz dont have dev environment available but I think you could do something like this...

 

class Category
{
   private $id_category;
   private $name;
}

class Product
{
// Product related vars.
   private $id_product;
   private $name;
   private $category; // Holds category object.
   
   function __construct()
   {
   		$this->category = new Category();
   }
}

 

EDIT: Actually it would be more logical to have an array of product objects in a category class than the above..

I think that I found a solution for it.

 

I've created a class called ProductList that extends Product which has all variables that doesn't belong to class Product.

For example, variable $category_name, a sum of values, etc.

 

Can I make by this way?

Or it is wrong?

 

Thanks

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.