Home  >  Q&A  >  body text

Rename Laravel relationship with same name in results

Here you can see I have two car_model main table fields and relationship names:

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: []
    }
    ...
}

When I try to get the car_model related relationship and have car_model at the same time, how do I get the relationship data? For example:

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

Product number:

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

and my query:

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

P粉163951336P粉163951336283 days ago535

reply all(2)I'll reply

  • P粉555682718

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

    I recommend that you rename the relationship to car_models or something other than car_model:

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

    And the query can be changed to this

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

    Then return

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

    reply
    0
  • P粉145543872

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

    I found the solution. After converting object to array, I can access car_model as relationship:

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

    or

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

    reply
    0
  • Cancelreply