1
I am trying to create the models in Lumen based on my current database for a virtual store, but I am having difficulties to configure the relationships between them.
So far I have the following Models:
*Product
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class Product extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'products';
public function productColor()
{
return $this->hasMany('ProductColor', 'id_product');
}
}
*Productcolor
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class ProductColor extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'product_colors';
public function sizeByProductColor()
{
return $this->hasMany('SizeByProductColor', 'id_product_color');
}
}
*Sizebyproductcolor
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class SizeByProductColor extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'sizes_by_product_color';
public function size()
{
return $this->hasMany('Size','id_size');
}
public function productColor()
{
return $this->belongsTo('productColor', 'id_product_color');
}
}
*Size
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class Size extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'sizes';
public function productColor()
{
return $this->belongsTo('SizeByProductColor');
}
}
My problem is that I’ve never worked with so many relationships and now this is giving me a lot of headache.
So I’m following the right path as the Models?
Note: Products have Colors and each product color has various shoe sizes and stock. Example:
If I needed to get the sizes for certain color I would use the following SQL:
SELECT * FROM sizes as s
LEFT JOIN product_colors as pc ON pc.id_color = 6
INNER JOIN sizes_by_product_color as sbpc ON s.id = sbpc.id_size AND pc.id = sbpc.id_product_color
How can I make this query in Controller?