return $this->belongsTo(User::class, 'landlord_id', 'id');
Jun 29, 2022
7
Level 2
ForeignIDs with different names
I don't know if this is acceptable
$table->foreignId('landlord_id')->constrained('users')->onDelete('cascade');
$table->foreignId('caretaker_id')->nullable()->constrained('users')->onDelete('cascade');
well this works when I query users with their properties the Issue is when I try to query properties and load the users/landlords
/**
* Get the landlord that owns the Property.
*/
public function landlord(): BelongsTo
{
return $this->belongsTo(User::class, 'landlord', 'id');
}
Level 80
@kevinwakhisi Your foreign key definitions are fine, but you’re using the wrong names in your Eloquent model. Your relation methods should look something like this if you’re using non-conventional names:
public function landlord(): BelongsTo
{
return $this->belongsTo(User::class, 'landlord_id');
}
The second argument is the name of the foreign key column. You named your foreign key column landlord_id; not just “landlord”.
1 like
Please or to participate in this conversation.