There is then a relationship Muitos para Muitos (N:M), where the tables Produto and Cores has an intermediate table with its respective keys:
Model Cor:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Cor extends Model
{
protected $table = 'cor';
protected $fillable = array('descricao');
protected $primaryKey = 'id';
public $timestamps = false;
//relação muitos para muitos.
public function produtos()
{
return $this->belongsToMany(Produto::class,'produto_cor','cor_id', 'produto_id');
}
}
Model Produto:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Produto extends Model
{
protected $table = 'produto';
protected $fillable = array('description', 'cor_id');
protected $primaryKey = 'id';
public $timestamps = false;
//relação muitos para muitos.
public function cores()
{
return $this->belongsToMany(Cor::class,'produto_cor','produto_id', 'cor_id');
}
}
In the Controller
public function index()
{
$id = 1; // código do produto
$result = Cor::leftJoin('produto_cor', function($join) use ($id)
{
$join->on('produto_cor.cor_id', '=', 'cor.id')
->where('produto_cor.produto_id', (int)$id);
})
->select(\DB::raw('cor.id, cor.descricao, if(produto_id is null, 0, 1) corstatus'))
->orderBy('cor.descricao')
->get();
return view('test.index', compact('result'));
}
in the variable $result return to color list with an extra field corstatus where corstatus = 1 to color is present in that product, not different.
And finally in View:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel - Test</title>
{{ Html::script('js/jquery.v1.11.0.js') }}
</head>
<body>
@foreach($result as $r)
<div>
<input @if((int)$r->corstatus==1) {!! 'checked="checked" ' !!} @endif type="checkbox" name="cor[]" value="{{$r->id}}">{{$r->descricao}}
</div>
@endforeach
</body>
</html>
I would make a
left joinof the table colors for the table of the relation, checked the ones that arenullwho are the ones who had no record, rode aforeachin the result with that difference– novic