2016-07-23 120 views
3

我正在做一個民意調查制度,我有兩個表:Laravel 5透視表的hasMany關係

  • 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:沒有與第一調查有關的選擇表中的許多選擇。

回答

0

此:

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'); 
} 
+0

但選擇只屬於一個民意調查並不多! 順便說一句,即使我改變了代碼,因爲你提到什麼都沒有發生 –

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:你必須改變BelongsToManybelongsToMany請注意0​​應該是小寫。

注2:您是否希望timestapms 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(); 

希望這有助於。