Simon El
Simon El

Reputation: 7

Laravel 5.4 table relationship between 3 small tables

I have a recently started learning Laravel 5.4, I am having trouble with my 3 way table relationship, I've looked at a few articles online regarding many to many, but this relationship is just a "hasOne" on both sides.

Could anyone give me a helpful hint as to how to structure my table relationship, here is the PK/FK relationship:

Users table     (id)

Listings table  (id, user_id)

Insights table  (id, listing_id) - one insight row per listing only.

And the models below:

Users Model

class User extends Model
{
    public function listing()
    {
        return $this->belongsTo('App\Listing');
    }
}

Listing Model

class Listing extends Model
{
    public function insight()
    {
        return $this->hasOne('App\Insight');
    }    
}

Insight Model

class Insight extends Model
{
    public function listing()
    {
        return $this->hasOne('App\Listing');
    }    
}

And what I am trying to achieve is to query the users own listings, with each listings current insights.

Thanks a bunch.

Simon.

Upvotes: 0

Views: 78

Answers (2)

ako
ako

Reputation: 2136

class User extends Model
{
    public function listing()
    {
        return $this->hasMany(Listing::class);
    }
}

class Listing extends Model
{
    public function insight()
    {
        return $this->hasOne(Insight::class);
    } 

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

class Insight extends Model
{
    public function listing()
    {
        return $this->belongsTo(Listing::class);
    }    
}

$users = User::with('listing.insight')->get();

foreach($users as $user) {
    $user->listing->insight;
}

Upvotes: 0

Morteza Rajabi
Morteza Rajabi

Reputation: 2913

User model

class User extends Model
{
    public function listing()
    {
        return $this->hasOne('App\Listing');
    }
}

Listing Model

class Listing extends Model
{
    public function insight()
    {
        return $this->hasOne('App\Insight');
    } 

    public function user()
    {
        return $this->belongsTo('App\User');
    }    
}

Insight Model

class Insight extends Model
{
    public function listing()
    {
        return $this->belongsTo('App\Listing');
    }    
}

And if you want query users with Listing and Insight

$users = User::with(['listing', 'listing.insight'])->get();

foreach($users as $user) {
    $user->listing->insight;
}

Upvotes: 1

Related Questions