第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何獲取從表數(shù)據(jù)中的主表數(shù)據(jù)有很多關(guān)系laravel 6資源

如何獲取從表數(shù)據(jù)中的主表數(shù)據(jù)有很多關(guān)系laravel 6資源

PHP
函數(shù)式編程 2023-10-01 17:07:57
我有兩個表,用戶(主)和產(chǎn)品(從),模型如下所示用戶型號: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');   }}產(chǎn)品型號: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'); }}產(chǎn)品的資源如下所示public function toArray($request) {  return [    'id' => $this->id,    'nama_produk' => $this->nama_produk,    'user_id' => $this->user_id,    'description' => $this->description  ]}控制器具有獲取所有產(chǎn)品的功能public function index(){    try {        $data = new ProductCollection(Product::all());        return response()->json($data);    } catch (\Throwable $th) {        return response()->json($th);    }}我的問題是 ProductResource 中的 user_id 返回一個數(shù)字(id),因為它與 User 表有關(guān)系,我希望結(jié)果返回類似這樣的內(nèi)容{  {    "id":1,    "nama_produk": "Bakso Goreng",    "user_id": {       "id":"1",       "name":"Andi",       "email":"andi@gmail.com",       "no_telpon":"00998422122"    },    "description":"Makanan berat"  }}因此, user_id 中有一個嵌套,其中包含添加產(chǎn)品的用戶的數(shù)據(jù),而不僅僅是數(shù)字(id),我該怎么做?
查看完整描述

1 回答

?
繁星coding

TA貢獻1797條經(jīng)驗 獲得超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

  ]

}


查看完整回答
反對 回復(fù) 2023-10-01
  • 1 回答
  • 0 關(guān)注
  • 110 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號