我有两个表,User(主)和Product(从),模型看起来像这样
用户模型:
class User extends Authenticatable {
protected $fillable = [
'name', 'email', 'password', 'api_token', 'role_id', 'no_telpon'
];
protected $hidden = [
'password', 'remember_token',
];
public function products()
{
return $this->hasMany('App\Product');
}
}
产品型号:
class Product extends Model
{
protected $table = 'products';
protected $guarded = ['id'];
protected $fillable = [
'nama_produk',
'user_id',
'description'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
产品的资源看起来像这样
public function toArray($request) {
return [
'id' => $this->id,
'nama_produk' => $this->nama_produk,
'user_id' => $this->user_id,
'description' => $this->description
]
}
控制器具有获取所有产品的功能
public function index()
{
try {
$data = new ProductCollection(Product::all());
return response()->json($data);
} catch (\Throwable $th) {
return response()->json($th);
}
}
我的问题是ProductResource中的user_id返回一个数字(id),因为它与User表有关系,我希望结果返回类似这样的内容
{
{
"id":1,
"nama_produk": "Bakso Goreng",
"user_id": {
"id":"1",
"name":"Andi",
"email":"andi@gmail.com",
"no_telpon":"00998422122"
},
"description":"Makanan berat"
}
}
因此,在user_id中有一个嵌套的容器,其中包含用户添加产品的数据,而不仅仅是数字(id),我该怎么做?
更新
这是我的产品集
class ProductCollection extends ResourceCollection
{
public function toArray($request)
{
return ProductResource::collection($this->collection);
}
}
答案 0 :(得分:1)
尝试一下:
public function index()
{
try {
$data = new ProductCollection(Product::with('user')->all());
return response()->json($data);
} catch (\Throwable $th) {
return response()->json($th);
}
}
编辑:
public function toArray($request) {
return [
'id' => $this->id,
'nama_produk' => $this->nama_produk,
'user_id' => $this->user_id,
'user' => $this->user,
'description' => $this->description
]
}
OR
public function toArray($request) {
return [
'id' => $this->id,
'nama_produk' => $this->nama_produk,
'user_id' => $this->user,
'description' => $this->description
]
}