2016-07-10 13:53
浏览 46

Laravel 5.2与数据透视表的关系

my tables:


  1. every part contain many of card.
  2. every card belong to many of part.

now,using laravel eloquent model how can fetch all card for a part without add more column to database

图片转代码服务由CSDN问答提供 功能建议


< / p>

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

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongshi9526 2016-07-10 15:53

    You need to define your relationships like below:

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

    Then you can fetch all the cards for a part like below:

    $cards = Part::with('cards')->find($part_id);
    打赏 评论
  • dqingn8836 2016-07-10 16:48
    Part::whereHas('cards', function($query) use ($cardId){
      $query->where('id', $cardId);  

    And your model relation should contain like this, for Part.php

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

    And for Card.php

    public function parts(){ 
     return $this->belongsToMany('App\Part');    
    打赏 评论

相关推荐 更多相似问题