Returning string data from a relationship only I have two tables.
Types - Contains three fields: id, name and path
Extensions - Among the fields is one named type_id - relates to the entry in Types
I first need to know the extension in order to get the path for the type. So I have a line of code in my method that looks like this:
// Get path
$ext = Extension::where('extension', $extension)->with('hasType')->first();
$path = $ext->hasType->path;
All I need is the path string. Is there a way to make a query using this relationship, but return only the path string of data I am seeking?
Looking to see what all I can do with these relationships.
Or do I need to create a separate method that does this for me, then return the string back to the method that needs it?
Hi there
I suggest spending a bit more time on naming relationships.
In the extension's model file add a method like this
public function getTypePathAttribute()
{
return $this->hasType->path // This relationship should be renamed to ->type instead of ->hasType.
}
and then use it in code like this
$extension->type_path;
If you think you're gonna use it a lot in your code you can append it to the model using $appends
https://laravel.com/docs/5.8/eloquent-serialization
protected $appends = ['type_path'];
Thanks for the reply.
I understand your thoughts about naming. Which probably comes easy with experience. This was my first time using relationships, so I sort of went off rails naming-wise, since I wasn't even sure how it all worked. Hence also the question at hand.
Thank you again for your thoughts.
If Extension has a column called type_id then this will be a belongsTo
Which means the relationship in Type is either hasOne or hasMany
So in Extension.php
public function type()
{
return $this->belongsTo(Type::class)
}
From extension to get path
$path = $extension->type()->path;
ps. public function getTypePathAttribute() is an accessor not a relationship, so don't know what that was all about.
Did you trying using select()?
$ext = Extension::where('extension', $extension)->with('hasType')->select('path')->first();
$path = $ext->path;
Please sign in or create an account to participate in this conversation.