How must define relationships between models?

Published 2 months ago by alihoushyaripour

Hi, For example I have three models with name 'User', 'Business', 'Post' and 'Review'. Now I want to define relationships between models. These are my migrations:

// user schema
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    ...
});

// business schema
Schema::create('businesses', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id'); // related to a user
    ...
});

// post schema
Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id'); // related to a user
    ...
});

// review schema
Schema::create('reviews', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id'); // related to a user
    $table->unsignedInteger('post_id'); // for a post
    ...
});

And these are my models class with relations:

// user model class
class User extends Model {
    ...
    public function business()
    {
        return $this->hasOne(Business::class);
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function reviews()
    {
        return $this->hasMany(Review::class);
    }
    ...
}

// business model class
class Business extends Model {
    ...
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    ...
}

// post model class
class Post extends Model {
    ...
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function reviews()
    {
        return $this->hasMany(Review::class);
    }
    ...
}

// review model class
class Review extends Model {
    ...
    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
    ...
}

But my code not work when i write an eloquent... I think my problem is that I have not followed these principles:

hasMany(related : string, [foreignKey : nulllstring = null], [localKey : nulllstring = null])
belongsTo(related : string, [foreignKey : nulllstring = null], [ownerKey : nulllstring = null], [relation : nulllstring = null])

According to this principle, my model relation functions should be change? For example in 'belongsTo', 'hasOne' and 'hasMany' should pass foreignKey of models as parameters?

Best Answer (As Selected By alihoushyaripour)
lostdreamer_nl

No, your models are exactly as they should be, named correctly, and using the correct naming conventions in the foreign keys so eloquent can 'guess' them.

It should be working correctly, so I'm guessing the problem is in 'your non working code'.

Post an example of something that you think should work, or test the following:

$user = new \App\User();
$user->name = "test";
$user->email = "[email protected]";
$user->password = bcrypt('secret');
$user->save();

$user->posts()->create([
    'title' => 'test post',
    'body' => 'This is an example post'   // change body if needed, and add other required fields...
]);

$users = User::with('posts')->get();

dd($users->toArray());
lostdreamer_nl

No, your models are exactly as they should be, named correctly, and using the correct naming conventions in the foreign keys so eloquent can 'guess' them.

It should be working correctly, so I'm guessing the problem is in 'your non working code'.

Post an example of something that you think should work, or test the following:

$user = new \App\User();
$user->name = "test";
$user->email = "[email protected]";
$user->password = bcrypt('secret');
$user->save();

$user->posts()->create([
    'title' => 'test post',
    'body' => 'This is an example post'   // change body if needed, and add other required fields...
]);

$users = User::with('posts')->get();

dd($users->toArray());
alihoushyaripour

@lostdreamer_nl Hi my friend,

My problem is not be solved yet, every time I call route show me this error:

"Call to undefined relationship [Post] on model [App\User]."

I tried all possible solutions, I became very confused...

What should I do !?

Cronix
Cronix
1 month ago (737,880 XP)

What should I do !?

Show your code with the issue!

But from the error, likely you used ->post() somewhere, but the relationship name in the user model is posts().

public function posts()
{
    return $this->hasMany(Post::class);
}
alihoushyaripour

Hi @Cronix

For example, this is other class,

// province model class
class Province extends Model
{
    public function cities()
    {
        return $this->hasMany(City::class);
    }
}

// province migration class
Schema::table('provinces', function ($table) {
    // parameters
    ...
});


// city model class
class City extends Model
{
    public function province()
    {
        return $this->belongsTo(Province::class);
    }
}

// city migration class
Schema::table('cities', function ($table) {
    // parameters
    ...

    // foreign key
    $table->foreign('province_id')->references('id')->on('provinces')->onDelete('restrict')->onUpdate('restrict');
});


// province repository class
class ProvincesRepository
{
    public function getWithCity()
    {
        return Province::with('City')->get();
    }
}

And error message shows when I called "getWithCity()" repository function:

"Call to undefined relationship [City] on model [App\Province]."
lostdreamer_nl
class Province extends Model
{
    public function cities()
    {
        ....
    }
}
return Province::with('City')->get();

That should be:

return Province::with('cities')->get();

Please sign in or create an account to participate in this conversation.