How must define relationships between models?

Posted 5 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?

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

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.