Laravel 5.4 3个小表之间的表关系

问题描述:

我最近开始学习Laravel 5.4,我在三向表关系方面遇到麻烦,我在网上看了几篇有关多对多关系的文章,但是这种关系在双方都是"hasOne".

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.

任何人都可以给我有关如何构建表关系的有用提示,这是PK/FK关系:

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.

以及以下型号:

用户模型

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

列表模型

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

洞察模型

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.

谢谢.

西蒙.

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;
}