I have 2 models, Building
and Apartment
. Building has a column named address
and apartment has a column named addresss
I want to add relation like this:
public function building() {
return $this->belongsTo(Building::class, 'addresss', 'address');
}
But then this gives null:
Apartment::first()->building
Even if this works:
Apartment::first()->building()->first()
So what should I do to get it to work using only this:
Apartment::first()->building
CodePudding user response:
If i kept it right the Apartment is part of the building?
That is why you set the Relation in Model Apartment:
public function building() {
return $this->belongsTo(Building::class, 'addresss', 'address');
}
When i use the belongsTo Relation, I just mention the class and do not append anymore inside the brackets like in this case:
public function user()
{
return $this->belongsTo(User::class);
}
What is the purpose of mentioning appartment's addresss aswell in the relation ? Have you set the foreign key's propely & set a hasMany Relationship in the Building-Model ?
Regards.
CodePudding user response:
The issue was I had a column in apartments table named building
, removing this fixed it