Using Laravel 10 and trying to get a belongsTo relationship to work and it’s not working. Basically a Fragment has one FragmentGroup while a FragmentGroup has many Fragments.
I’m using it this way and it’s giving me null:
$fragment = Fragment::find(1);
return $fragment->fragmentGroup->name;
class Fragment extends Model {
public function fragmentGroup(): BelongsTo
{
return $this->belongsTo(FragmentGroup:class, 'FragmentID');
}
}
class FragmentGroup extends Model {
public function medicine_type(): HasMany
{
return $this->hasMany(Fragment:class, 'FragmentGroupID');
}
}
Database structure
Fragment:
FragmentID
FragmentGroupID
Name
FragementGroup
FragmentGroupID
Name
3
Answers
The way you are using the method is not correct.
Anyways, to use it you would need to change
to
$fragment should now have
fragment_group
as part of the collection.You can check if you
dd($fragment);
If you can see
fragment_group
but it has blank array/object as its value, then check the methods used inside model.In your original code, there is a typing mistake in ‘FragmentGroup:class‘. It should be ‘FragmentGroup::class‘.
Also, you can pass the
foreign_key
andlocal_key
to further specify.Your function should be:
I think it will be solve your problem.
replace
to
Since fragmentGroup doesn’t load automatically, you should access it not as an attribute (fragmentGroup), but through the fragmentGroup() method.