我有这个控制器,它具有2种关系:组和组一起开玩笑
public function find($name){
$locate= Products::where('name', 'like', "$name%")->with('groups.group')->get();
return response()->json($locate, 200);
}
有了这个,我回来了:
[{
"name":"Test",
"code":"123",
"price":"321.00",
"created_at":null,
"updated_at":null,
"groups":{
"id":1,
"product_id":1,
"group_id":2,
"created_at":null,
"updated_at":null,
"group":{
"id":2,
"name":"Test",
"desc":"dasdasdsa",
"commission_s":2,
"commission_m":2,
"created_at":null,
"updated_at":null
}}}]
最大的问题是,我不希望“组”对象只是一个关系表。
模型:
class Products extends Model
{
protected $fillable = ['name', 'code', 'price'];
protected $hidden = ['id'];
public function Groups()
{
return $this->hasOne('App\pGroup', 'product_id', 'id');
}
}
Pgroup模型
class pGroup extends Model
{
protected $fillable = ['group_id', 'product_id'];
public function Group()
{
return $this->belongsTo('App\ProductGroup');
}
}