亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取從表數據中的主表數據有很多關系laravel 6資源

如何獲取從表數據中的主表數據有很多關系laravel 6資源

PHP
函數式編程 2023-10-01 17:07:57
我有兩個表,用戶(主)和產品(從),模型如下所示用戶型號: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":"[email protected]",       "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

  ]

}


查看完整回答
反對 回復 2023-10-01
  • 1 回答
  • 0 關注
  • 121 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號