Home > Software design >  Return only single column from Laravel hasOne relation
Return only single column from Laravel hasOne relation

Time:11-25

I'm creating custom form fields and in one table I save the field types, ex:

CustomFieldTypes
-------------------------------
id |    type     | common_name
-------------------------------
1  | v-text-area | TextArea
-------------------------------

Then in another table I save the details of the created custom field, ex:

PageCustomFields
----------------------------------------------------------
id | page_id | custom_field_type_id | label | is_required
----------------------------------------------------------
2  |    2    |          1           | Name  | false
----------------------------------------------------------

When I retrieve the PageCustomFields model I want to include ONLY the CustomFieldType's "type" field, I don't need the other field. How can I accomplish this? I've tried something like this in the PageCustomFields model but it doesn't seem to work:

public function customFieldType(){
   return $this->hasOne(CustomFieldType::class, "id", "custom_field_type_id")->select('type');
}

Any advise? Thanks!

CodePudding user response:

Out of my head; does this work?

public function customFieldType(){
   return $this->hasOne(CustomFieldType::class, "id", "custom_field_type_id")->type;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If not, assuming you're using Vue as a front end, perhaps you could use Laravel Resources to filter out only the information you want.

CodePudding user response:

I think you relation should be:

public function customFieldType(){
   return $this->belongsTo(CustomFieldType::class, "custom_field_type_id");
}

I prefer to define relationships without constraints, then apply needed constraints in controllers' code:

$value=PageCustomField::with('customFieldType:id,type')->get();

note this will select only id(needed for loading) and type.

anyway , if you want it that way you can use addSelect:

 public function customFieldType(){
       return $this->belongsTo(CustomFieldType::class, "custom_field_type_id")->addSelect(['CustomFieldTypes.id','CustomFieldTypes.type']);
    }
  • Related