Show in json a relationship

0

I'm making a system that exists a product register, these same products can be part of just 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 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 products controller.

public function find($nome){
    $locate= Products::where('nome', 'like', "$nome%")->with('groups.group')->get();

    return response()->json($locate, 200);
}

As you can see, it seems to be all right. The problem is that in json it creates two arrays of objects, a "Groups" it pulls the data from the pGroup table, which is a table that contains only the referenced ids and in the other object "Group" it pulls the data I want, which is the name of this group.

How do I display only an object containing the name of the group the product is in, passing the foreign key.

    
asked by anonymous 10.11.2018 / 01:39

0 answers