我有两个表,用户(主)和产品(从),模型如下所示用户型号: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),我该怎么做?
1 回答
繁星coding
TA贡献1797条经验 获得超4个赞
尝试这个:
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
]
}
或者
public function toArray($request) {
return [
'id' => $this->id,
'nama_produk' => $this->nama_produk,
'user_id' => $this->user,
'description' => $this->description
]
}
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消