首頁  >  問答  >  主體

在結果中為相同名稱的Laravel關係重新命名

在這裡,你可以看到我有兩個 car_model 主表欄位和關係名稱:

AppModelsProduct {#1478 ▼
  #connection: "mysql"
  #table: "products"
  ...
  #escapeWhenCastingToString: false
  #attributes: array:21 [▼
    "id" => 1
    "company_id" => 1
    ...
    "car_model" => "test"
    ...
  ]
  #original: array:21 [▶]
  ...
  #relations: array:5 [▼
    "company" => AppModelsCompany {#1506 ▶}
    "car_model" => AppModelsCarModel {#1508 ▼
      #connection: "mysql"
      #table: "car_models"
      #attributes: array:6 [▼
        "id" => 1
        "title" => "test"
        "created_at" => ":07:25"
        "updated_at" => ":07:58"
      ]
      ...
      +mediaConversions: []
      +mediaCollections: []
      #deletePreservingMedia: false
      #unAttachedMediaLibraryItems: []
    }
    ...
}

當我嘗試取得 car_model 相關關係並同時擁有 car_model 時,我該如何取得關聯式資料?例如:

$products->first()->car_model->title

產品型號:

    public function car_model(): BelongsTo
    {
        return $this->belongsTo(CarModel::class);
    }

和我的查詢:

$this->products = Product::with(
    [
        'car_model',
    ]
)->get();

P粉163951336P粉163951336333 天前569

全部回覆(2)我來回復

  • P粉555682718

    P粉5556827182023-12-16 08:19:45

    我建議您將關係重新命名為 car_models 或 car_model 之外的其他名稱:

    public function car_models(): BelongsTo
        {
            return $this->belongsTo(CarModel::class);
        }

    並且查詢可以更改為這樣

    $this->products = Product::with(
        [
            'car_models',
        ]
    )->get();

    然後回傳

    $products->first()->car_models->title

    回覆
    0
  • P粉145543872

    P粉1455438722023-12-16 00:19:13

    我找到了解決方案。將 object 轉換為 array 後,我可以將 car_model 作為 relationship 存取:

    $i=$products->first()->toArray();
    echo $i['car_model']['title'];
    

    echo ($products->first()->toArray())['car_model']['title']
    

    回覆
    0
  • 取消回覆