【问题标题】:Laravel 5 using pivot table with hasMany relationshipLaravel 5 使用具有 hasMany 关系的数据透视表
【发布时间】:2016-11-27 13:46:54
【问题描述】:

我正在制作一个投票系统,我有两张桌子:

  • polls 表:具有这些字段 (id,question,created_at,updated_at)。

  • choices 表:具有这些字段 (id,poll_id,choice)。

还有一个名为 choice_poll 的数据透视表:具有这些字段 (id,choice_id,poll_id,ip,name,phone, comment ,created_at,updated_at)

投票模型:

class Poll extends Model 
{

    protected $table = 'polls';
    protected $fillable = ['question'];
    public $timestamps = true;

    public function choices()
    {
      return $this->BelongsToMany('App\Choice')->withPivot('ip','name','phone','comment');
    }
}

选择模型:

class Choice extends Model 
{

    protected $table = 'choices';
    protected $fillable = ['poll_id','choice'];
    public $timestamps = false;

    public function poll()
    {
      return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
    }
}

现在,当我尝试构建此查询时,它不会返回选项:

$poll->first()->choices()->get()

PS:与第一次投票相关的选项表中有很多选项。

【问题讨论】:

    标签: php mysql laravel laravel-5 eloquent


    【解决方案1】:

    在这种情况下,您有 Many To Many 关系,因此请尝试将belongsTo 更改为:

    public function poll()
    {
        return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
    }
    

    belongsToMany,会是:

    public function poll()
    {
        return $this->belongsToMany('App\Poll')->withPivot('ip','name','phone','comment');
    }
    

    注意 1:您必须将 BelongsToMany 更改为 belongsToMany 注意 B 应为小写。

    注意 2:您想要带有时间戳的数据透视表 create_at,updated_at,正如您在 OP 中提到的那样,您必须使用 withTimestamps();

    return $this->belongsToMany('App\Poll')
                ->withPivot('ip','name','phone','comment')
                ->withTimestamps();
    
    //AND in the other side also
    
    return $this->belongsToMany('App\Choice')
                ->withPivot('ip','name','phone','comment')
                ->withTimestamps();
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      这个:

      public function poll()
      {
        return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
      }
      

      public function choices()
      {
        return $this->BelongsToMany('App\Choice')->withPivot('ip','name','phone','comment');
      }
      

      应该是:

      public function poll()
      {
        return $this->belongsToMany('App\Poll')->withPivot('ip','name','phone','comment');
      }
      

      public function choices()
      {
        return $this->belongsToMany('App\Choice')->withPivot('ip','name','phone','comment');
      }
      

      【讨论】:

      • 但选择只属于一项民意调查,不多!!顺便说一句,即使我改变了你提到的代码,也没有发生任何事情
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 2020-08-22
      • 2014-09-29
      相关资源
      最近更新 更多