繁体   English   中英

Laravel 5.2与数据透视表的关系

[英]Laravel 5.2 relationship with pivot table

我的桌子:

桌子

  1. 每个部分都包含许多卡片。
  2. 每张卡都属于很多部分。

现在,使用laravel雄辩的模型,如何在不向数据库添加更多列的情况下获取零件的所有卡

您需要定义您的关系,如下所示:

class Part extends Model
{
    public function cards()
    {
        return $this->belongsToMany('App\Cards', 'user_cards');
    }
}

然后,您可以获取所有卡,如下所示:

$cards = Part::with('cards')->find($part_id);
Part::whereHas('cards', function($query) use ($cardId){
  $query->where('id', $cardId);  
})->get();

并且您的模型关系应该包含​​这样的部分(对于Part.php)

public function cards(){ 
 return $this->belongsToMany('App\Card');    
}

对于Card.php

public function parts(){ 
 return $this->belongsToMany('App\Part');    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM