In my User model i have 2 relationships
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
The second City doesnt work when i use
$user = App\User::findorfail(1)->with('city')->first();
for example. It gives the message
Illuminate/Database/Eloquent/RelationNotFoundException with message 'Call to undefined relationship [city] on model [App/User].
Class City is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class City extends Model
{
use SoftDeletes;
protected $fillable = ['name', 'nomos_id','user_id'];
protected $table = 'cities';
public function setNomosIdAttribute($input)
{
$this->attributes['nomos_id'] = $input ? $input : null;
}
public function nomos()
{
return $this->belongsTo(Nomoi::class, 'nomos_id')->withTrashed();
}
}
What is the problem? Why one relationship works and the other doesnt.
Looking at the code
$this->belongsTo(City::class, 'city_id')as an inverse of hasOne relationship that eventually would be looking at a city that the "user belongs to"?Is this the intended purpose of this relation structure? If it is the inverse of it where as, we are looking for a city that "belongs to the user" we should be using
$this->hasOne(City::class, 'city_id')of$this->hasMany(City::class, 'city_id')if it's a one-to-many relation.