0
I am making a system that there is a register of products, these products the same can be part of only one group, or not.
I have this model for Products:
class Products extends Model
{
protected $fillable = ['nome', 'codigo', 'preco'];
protected $hidden = ['id'];
public function Groups()
{
return $this->hasOne('App\pGroup', 'produto_id', 'id');
}
}
And this model where I store the products that have a group
class pGroup extends Model
{
protected $fillable = ['group_id', 'produto_id'];
public function Group()
{
return $this->belongsTo('App\ProductGroup');
}
}
In this pGroup model I just saved the product id and group id as a Foreign key.
Now, let’s go to the product controller.
public function find($nome){
$locate= Products::where('nome', 'like', "$nome%")->with('groups.group')->get();
return response()->json($locate, 200);
}
As you can see, everything looks right. The problem is that in json it creates two object arrays, a "Groups" it pulls the data from the pGroup table, which is a table that contains only the referenced ids and in the other "Group" object it pulls the data I want, which is the name of that group.
How do I display only one object containing the group name the product is in, passing through the Foreign key.
if you have to do an Inner Join then!
– novic
Take a look at this piece of documentation and I think it can help you by building relationships with "Hasmany": https://laravel.com/docs/5.7/eloquent-relationships#has-Many-through
– Wellington Rogati