2017-10-06 101 views
2

我玩laravel首次,我就如何实现一个链接表的关系有点困惑。我有3个表:坦克,TankContent内容一个链接表Laravel关系 - 困惑

我有以下型号:

坦克:

class Tank extends Model 
    { 
     public function getTankContent() 
     { 
      return $this->hasMany('App\TankContent', 'tankID', 'tankID'); 
     } 
    } 

TankContent:

class TankContent extends Model 
{ 
    public function getTank() 
    { 
     return $this->belongsTo('App\Tank', 'tankID', 'tankID');  
    } 

    public function getContent() 
    { 
     return $this->belongsTo('App\Content', 'contentID', 'contentID'); 
    } 
} 

内容:

class Content extends Model 
{  
    public function getContentTanks() 
    { 
     return $this->hasMany('App\ContentTank', 'contentID', 'contentID'); 
    } 
} 

现在我试着打电话说tankID 2和获取

$content = Tank::find(2); 
$items = $content->getTankContent; 

这里面所有的内容细节将列出我的内容。但是,那么我怎样才能将结果链接到TankContent模型的getContent()

在此先感谢。希望我只是需要它解释,然后它会全部点击。

P.S我曾尝试阅读https://laravel.com/docs/5.5/eloquent-relationships#many-to-many和IM仍然难倒!

回答

0

TankContent不是必需的,belongsToMany关系方法属于在坦克和内容模式。

https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

从这里也可以看有没有RoleUser模型中,模型只是角色和用户。这些模型上的belongsToMany关系定义中间表或角色表是role_user。

可以额外定义与withPivot这种关系()链接到所述belongsToMany方法等领域。 (请阅读“检索中间表列”)。因此,可能没有理由为中间/数据透视表建立单独的模型。

+0

我应该预先指定TankContent的其他字段就像DateAdded。所以它是一个链接表,但可能有一个坦克中的每种类型的内容需要一个日期戳4件物品 – JustinDonnnelly

+0

@JustinDonnnelly,你读过我答案的最后一段吗? – Devon

+0

对不起,这只是烦我!我现在就试试:) – JustinDonnnelly