首页  >  问答  >  正文

在结果中为相同名称的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粉163951336332 天前568

全部回复(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
  • 取消回复